Home > Software engineering >  Why is my jQuery text.replace() function skipping some characters in strings
Why is my jQuery text.replace() function skipping some characters in strings

Time:01-12

We have a carousel with some captions on each slide, and a function that checks for the letters LUMAX in each of the captions wrapped in an H4 tag and wraps the letter in a SPAN tag.

const arr = ['l','u','m','a','x'];
const re = new RegExp(`\\b${arr.join("|")}\\b`,"gi");
$("h4").html((_,text) => text.replace(re,match => `<span>${match}</span>`));

I thought this was working correctly, but on closer inspection it is not working for all characters. For instance - on the first slide all is good, but on the second slide the caption reads:

<h4>Love has no labels</h4>

For some reason it outputs like this

<h4><span>L</span>ove h<span>a</span>s no <span>l</span><span>a</span>bels</h4>

As you can see the first and second "L" are wrapped in SPAN tags, however the third instance of the letter L is not.

I tried rewriting the function in vanilla Javascript but this didn't work either.

CodePudding user response:

Remove boundary \b from your regex and all is well.

Example:

const arr = ['l', 'u', 'm', 'a', 'x'];
const re = new RegExp(`${arr.join("|")}`, "gi");

$("h4").html((_, text) => text.replace(re, match => `<span>${match}</span>`));
span {
  color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>Love has no labels</h4>

  • Related