1

I have a regular expression happening that searching for all the capitals in a document. It gathers them and puts them into an array no problem.

The issue I am having is I want to replace the items in that array to include a span around each item that was captured in the array and then display the updated result. I've tried a variety of things.

I am at a complete loss. Any help is appreciated. Here was my last attempt

var allCaps = new RegExp(/(?:[A-Z]{2,30})/g);
    var capsArray = [];
    var capsFound;

    while (capsFound = allCaps.exec(searchInput)) {
        capsArray.push(capsFound[0]);
    }


    //for(var x = 0; x < capsArray.length; x++){

            //var test = ;
            capsArray.splice(0, '<span style="color:green">'+ capsArray +'</span>');

    //}
}
1
  • 2
    Did you mean capsFound === allCaps.exec(searchInput) Commented Sep 18, 2017 at 15:03

3 Answers 3

5

You can't convert an entire array's elements like that using splice - you can use .map instead:

capsArray = capsArray.map(c => '<span style="color:green">' + c + '</span>');
Sign up to request clarification or add additional context in comments.

Comments

1

Do you need the results in an array? If not, you can wrap all caps in a str using a modified regex:

str.replace(/([A-Z])/g, '<span>$1</span>')

example:

'A--B--C' becomes '<span>A</span>---<span>B</span>---<span>C</span>'

if the array is needed for whatever reason:

str.split(/[^A-Z]+/g).map(x => `<span>${x}</span>`)

example:

'A--B--C' becomes ['<span>A</span>', '<span>B</span>', '<span>C</span>']

1 Comment

there's also the version of .replace that takes a callback function
0

Thanks to everyone for the help.

Heres my final solution for anyone else that gets lost along the way

var allCaps = new RegExp(/(?:[A-Z]{2,30})/g);
var capsArray = [];
var capsFound;

while (capsFound = allCaps.exec(searchInput)) {
    capsArray.push(capsFound[0]);
}

if(capsArray.length > 0){
    resultsLog.innerHTML += "<br><span class='warning'>So many capitals</span><br>";
    searchInput = document.getElementById('findAllErrors').innerHTML;
    searchInput = searchInput.replace(/([A-Z]{3,30})/g, '<span style="background-color:green">$1</span>');
    document.getElementById('findAllErrors').innerHTML = searchInput;
}
else {
    resultsLog.innerHTML += "";
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.