renathy
renathy

Reputation: 5355

Match and replace by regex, but do replace only for some part found by regexp

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:

For 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

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

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

Related Questions