Javascript Regular Expressions replace words

Description

Javascript Regular Expressions replace words

let myString = "Paul, Paula, Pauline, paul, Paul"; 
let myRegExp = /Paul/gi; 

myString = myString.replace(myRegExp, "Ringo"); 
console.log(myString); /* ww  w  . j  a v a 2  s. c om*/

You used this code to convert all instances of Paul or paul to Ringo.

This code actually converts all instances of Paul to Ringo, even when the word Paul is inside another word.

One way to solve this problem would be to replace the string Paul only where it is followed by a non-word character.

let myString = "Paul, Paula, Pauline, paul, Paul"; 
let myRegExp = /Paul\W/gi; 

myString = myString.replace(myRegExp, "Ringo"); 
console.log(myString); /*from   w w w .j  a va  2 s .c  o  m*/

It's getting better, but it's still not what you want.

Let's alter the regular expression to deal with the last Paul:

let myString = "Paul, Paula, Pauline, paul, Paul"; 
let myRegExp = /Paul\b/gi; 

myString = myString.replace(myRegExp, "Ringo"); 
console.log(myString); //  w  ww .  j  a  v a2  s . co  m



PreviousNext

Related