Skip to content
Advertisement

regexp highlight search matching numbers

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?

JavaScript

https://jsfiddle.net/rrggrr/kgd4swha/6/

Advertisement

Answer

Here’s a simple way of doing it:

Use a string#replace using /(9756[0-9]{8})/g as the regex to capture the value (don’t forget the g to 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.

JavaScript
JavaScript
JavaScript

As a note, the problem in the original post is that the string#split function 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 use string#matchAll on 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#replace is 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+/g with a function as the replacement value so that we can do the regex#test within the replacement.

If you want to limit the numbers that get checked, you could modify the /d+/g to change what are being replaced.

JavaScript
JavaScript
JavaScript

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.

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement