I've got a script from a friend, and tried to modified it. So that it highlights a string of numbers in a div.
The problem is, that the output of the highlighted text becomes the regexp. Any solutions, what I'm doing wrong?
var list = document.getElementsByClassName("message__content")
var search_word = RegExp(/9756[0-9]{8}/);
var contents = []
for(var i = 0; i < list.length; i++){
var contents = list[i].textContent.split(search_word)
var elem = '<span class="highlight">'+search_word+'</span>'
list[i].innerHTML = contents.join(elem)
}
Here's a simple way of doing it:
Use a
string#replaceusing/(9756[0-9]{8})/gas the regex to capture the value (don't forget thegto indicate that it's a global regex so it'll run for every match in the input string), then a replace of'<span class="highlight">$1</span>'to use the first capture group and apply the markup.As a note, the problem in the original post is that the
string#splitfunction doesn't actually save the text that was removed as part of the split, so if you wanted to go that route, you'd have to usestring#matchAllon the side, and then map over the indexes to put everything together properly.I took a look at doing this originally before I realized that
string#replaceis a cleaner solution in this instance.From a comment, here's a way to conditionally set button classes based on if a regex matches.
If the goal is to check if every number in the text matches the regex, then we can use a regex replace for
/\d+/gwith a function as the replacement value so that we can do theregex#testwithin the replacement.If you want to limit the numbers that get checked, you could modify the
/d+/gto change what are being replaced.Another possibility intead of checking every number is to split on a value and then map over the resulting values. I'm just including this as it's helpful for something that's simple to split.