Reputation: 5355
I have to match string for specific regexp and do replace (replace with nothing). However, during replace I have to replace only part of regexp matched. See below.
I have the following regexp:
var regex1 = RegExp('[\s.,:\*]+' + word + '?s?i?\s*:?\s*', 'gi');
This regexp should match (at least, I hope so) all occurences of:
word
whitespace, dot, comma, : or *
symbol exactly before this word [\s.,:\*]+
and no other symbols in between this and word
s
and i
letters) exactly after the word '?s?i?\s*:?\s*'
and nothing elseFor instance, matches would be .testword
; ,testwords
; :.testword
.
I am replacing these occurences with "nothing": str = str.replace(regex1, "")
.
However, I do not need to replace first part: [\s.,:\*]+
. I want it to stay. So in string
"Some words .testword"
should be "Some words ."
I have "Some words" (there is no dot at the end).
Upvotes: 1
Views: 1279
Reputation: 626748
Note that you must define \
in a string literal with double \
. '[\s.,:\*]+'
=> '[\\s.,:*]+'
. Wrap it with a capturing group and use a backreference in the replacement. RegExp('([\\s.,:*]+)' + word + 's?i?\\s*:?\\s*', 'gi');
and replace with "$1"
, not ""
.
var s = "Some words .testword";
var word="testword";
var rx = RegExp('([\\s.,:*]+)' +word + 's?i?\\s*:?\\s*', 'gi');
console.log(s.replace(rx, "$1"));
The $1
will insert the part of string "sub"matched with the ([\\s.,:*]+)
regex part.
Upvotes: 1