Reputation: 113
I have this bit of code that searches through a user input and then highlights all the uppercase text. I've used a RegExp and splice to do the replace, but I can't seem to figure out how to show the results on screen, only in the console.
var allCaps = new RegExp(/(?:[A-Z]{3,30})/g);
var capsArray = [];
var capsFound;
var capitalErrorsList = '';
while (capsFound = allCaps.exec(searchInput)) {
capsArray.push(capsFound[0]);
}
if(capsArray.length > 0){
resultsLog.innerHTML += "<p><span class='warning'>Is this an abbreviation? If yes, ensure you have the full version included after its first use.</span></p>";
for(var five = 0; five < capsArray.length; five++) {
//display associated text
capitalErrorsList += '<li>' + capsArray[five] + '</li>';
capsArray.splice(0, 1, '<span style="background-color: yellow;">'+capsArray[five]+'</span>');
console.log(capsArray);
}
resultsLog.innerHTML += '<ul>' + capitalErrorsList + '</ul>';
}
else {
resultsLog.innerHTML += "";
}
Adding in this bit of code was the closet I got, but it gave some very odd results.
searchInput = document.getElementById('findAllErrors').innerHTML;
searchInput = searchInput.replace(capsArray[five], function(){
return capsArray.splice(0, 1, '<span style="background-color: yellow;">'+capsArray[five]+'</span>');
});
Upvotes: 0
Views: 45
Reputation: 361
I think you might have a case of the XY problem.
If you want to highlight the caps in that input, then you're right in wanting to wrap them in a <span>
. However, if you went to all the trouble of using regex, how about a regex replace?
var searchInput = document.getElementById('searchInput').innerText;
var replacedText = searchInput.replace(/(?:[A-Z]{3,30})/g, '<span style="background-color: yellow;">$&</span>');
document.getElementById('findAllErrors').innerHTML = replacedText;
Here's an updated fiddle for you.
If you're set on your array operations, map()
creates a new array by applying a function to the input array. So, for your example:
var highlighted = capsArray.map(function(caps) {
return '<span style="background-color: yellow;">' + caps + '</span>';
});
Upvotes: 1