It's easy to confuse, but a RegExp literal and a string of a RegExp literal will often have differently escaped characters. Because you're using a literal, you don't need to escape every backslash, since RegExp will interpret them properly.
In this case, don't double your backward slashes \
, since that resolves to matching a plain backslash \
; you're looking to use just \s
, which will resolve directly as the escape sequence for any whitespace:
var string = 'some random text :word: some text after';
console.log(string.replace(/:\s*(word)\s*:/g, '_REPLACEMENT_'));
If you're looking for any word, not just the actual string word
, then use the RegExp sequence [a-zA-Z]*
instead of (word)
, which will match a sequence of any number of alpha characters:
var string = 'some random text :newWord: some text after';
console.log(string.replace(/:\s*[a-zA-Z]*\s*:/g, '_REPLACEMENT_'));