Search code examples
javascriptregexmathcontext

How to replace all instances of a substring but only whole worlds in JS?


For example this function

function replaceAll(str,x,y){
    return str.split(x).join(y);
}

var x="My cat have a hat a its head.";

replaceAll(x,"at","on")

will return from this

My cat have a hat at its head.

to this

My con have a hon on its head.

but i want to return with

My cat have a hat on its head.


Solution

  • Define your function like this with word boundary regex:

    function replaceAll(str,x,y){
        return str.split(new RegExp("\\b"+x+"\\b")).join(y);
    }
    

    Then:

    repl = replaceAll(x,"at","on")
    //=> My cat have a hat on its head.