-1

I have a word for example "word" and if it has characters ':' before and after I need to replace it by other value;

var string = 'some random text :word: some text after';

I've tried

string = string.replace(/:\\s*(word)\\s*:/g, value);

But with no success

Sasha Zoria
  • 739
  • 1
  • 9
  • 28

2 Answers2

0

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_'));
zcoop98
  • 2,590
  • 1
  • 18
  • 31
  • @weltschmerz I edited my explanation for clarity, how's that? – zcoop98 Sep 22 '20 at 15:36
  • Yup good........ – Dennis Hackethal Sep 22 '20 at 15:39
  • It's also on me, I misread "shouldn't escape characters like you would in strings" as "shouldn't escape characters at all in regexes, that's only done in strings" whereas you meant "not *like* it's done in strings," as in, "the escaping works differently in strings and regexes," which is, of course, perfectly correct. – Dennis Hackethal Sep 22 '20 at 15:54
0

There's no need for the capture group, since you're not copying the word into the replacement.

The escaped backslash will match a literal backslash, but you don't have that in your input. If you want to match whitespace, it should just be \s, not \\s.

If you want to include the : in the result, just concatenate them to the replacement value.

var string = 'some random text :word: some text after';
var value = 'replacement';
string = string.replace(/:\s*word\s*:/g, ':' + value + ':');
console.log(string);
Barmar
  • 741,623
  • 53
  • 500
  • 612