Use JavaScript to replace all characters in string with "p" except "o"

82 views Asked by At

I would like to replace all characters in a string myString with "p", except "o".

For example:

"fgyerfgehooefwfweeo"

should become

"pppppppppoopppppppo"

I tried:

myString.replaceAll('[^o]*/g', 'p')
2

There are 2 answers

1
Unmitigated On BEST ANSWER
  • Pass a regular expression literal instead of a string to replace (or replaceAll).
  • Do not use * after the character class; otherwise, multiple consecutive characters that are not "o" will be collapsed into a single "p".

let str = "fgyerfgehooefwfweeo";
let res = str.replace(/[^o]/g, 'p');
console.log(res);

1
XMehdi01 On

Simple way without using Regex: which String.split() the string into chars and do Array.map() with condition on letter 'o' then finally Array.join() them back.

console.log("fgyerfgehooefwfweeo".split('').map(chr => chr !== 'o' ? 'p' : chr).join(''))