0

I have a JS function that replaces a (full) word in a string:

var replaceWord = function(str,src,tgt){
    var regex =  new RegExp("\\b"+src+"\\b","g"); 
    return str.replace(regex, tgt);
}

However it does not work when surounded by non-alpabeticall characters, for example:

let txt= "The 'great' idea of today ";
let word = "'great'";
let out = replaceWord(txt,word,"|test|");
console.log(out);

The output remains unchanged from the original. The desired output should have been:

The |test| idea of today

How can I change the function in order to have an accurate replacement function?

Help appreciated

Patrick
  • 383
  • 1
  • 2
  • 19
  • You need to escape the `|` in your regex since you're building it as a string. – Andy Ray Mar 09 '23 at 06:43
  • 1
    @AndyRay There's no `|` in the regex. The problem is that word boundaries (`\b`) only work on "word characters" (`\w`). – Robby Cornelissen Mar 09 '23 at 06:44
  • 1
    Ah, it's because a word boundary is between a `\w` and a `\W` character, and both a space and a `'` are `\W` characters. So it's working as intended, depending on what you need to do, you need to special case handle non-word characters in your search. – Andy Ray Mar 09 '23 at 06:45

0 Answers0