carb0nshel1 carb0nshel1 - 2 months ago 10
Javascript Question

Why is RegEx ignoring the second match if immediately following the first?

I have a string:

'4 0 13 0 0 30 32 0 14 9 27 0 27 20 4 0 22 0'
. The value I want my RegEx to find is contained within a variable named
targetValue
.
In this case
targetValue
happens to equal
0
and I want all matches to be replaced with bolder text. Here is the basic code:



function startReplacing(){
var targetValue = 0;
var replacer = ' <b> ' + targetValue + ' </b> ';
var re = new RegExp('\\s'+targetValue+'\\s','gi');

var str = document.getElementById('string').innerHTML;
str = str.replace(re, replacer);

document.getElementById('string').innerHTML = str;
}

b{ font-size:125% }

<p id="string"> 4 0 13 0 0 30 32 0 14 9 27 0 27 20 4 0 22 0 </p>
<button onclick="startReplacing()">REPLACE</button>





After clicking "REPLACE" Do you notice the "0" before the value "30"? My RegEx missed this value. How can I change my code to fix this?

Note: My RegEx Misses all values that should match immediately following a first match.

Answer

Your regex tries to match a space before the number and after the number. If there is only one space between two numbers, it cannot match them both.

I suspect you don't want to match the whitespaces at all, and just need to check that there's no other digit. Use a word boundary for that:

function startReplacing(){
  var targetValue = 0;
  var replacer = ' <b> ' + targetValue + ' </b> ';
  var re = new RegExp('\\b'+targetValue+'\\b','g');
//                     ^^^               ^^^

  var str = document.getElementById('string').innerHTML;
  str = str.replace(re, replacer);

  document.getElementById('string').innerHTML = str;
}
b{ font-size:125% }
<p id="string">4 0 13 0 0 30 32 0 14 9 27 0 27 20 4 0 22 0</p>
<!-- works without leading and trailing spaces even -->
<button onclick="startReplacing()">REPLACE</button>