Search code examples
javascriptregexreplaceallexcept

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


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')

Solution

    • 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);