Search code examples
javascriptregexword-boundary

Regex defining boundary but not capturing it to replace - javascript


I have the following string:

"i like ??dogs? and cats"

I want to identify the substring ??dogs? and replace it for something else, let's say "?birds".

So I created this function to do it:

function strUnderline (str, oldword, newword) {
                    str = str.replace(new RegExp('(^|[-,.!?:;"\'\(\\s])' + oldword + '(?=$|[-?!,.:;"\'\)\\s])'), "$1" + newword)
            return str;
        };

But when I run:

strUnderline("i like ??dogs? and cats", "??dogs?", "?birds")

i get:

"i like ???birds? and cats"

I want to define word boundaries and also capture them.

Any suggestions?


Solution

  • If you want to replace all the occurrences of a oldWord, you need to escape the question marks:

    function strUnderline(str, oldWord, newWord) {
      oldWord = oldWord.replace(new RegExp(/\?/g), "\\?");
      return str.replace(new RegExp(oldWord, 'g'), newWord);
    }
    
    let input = "i like ??dogs? and cats, but especially ??dogs?";
    let output = strUnderline(input, "??dogs?", "?birds");
    console.log(output);

    For a more general regex, that escapes all special characters, read this.