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

77 Views Asked by At

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.

1

There are 1 best solutions below

0
On BEST ANSWER

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.