Phil
Phil

Reputation: 7597

Javascript regular expression: save matching value

I have the following expression in JS (typescript, but I think everyone understands what it transpiles to):

  markString(text: string) {
    const regEx = new RegExp(this.partToHighlight, 'ig');
    return text.replace(regEx, `<mark>${this.partToHighlight}<\/mark>`);
  }

The problem is that this way, with the 'ig'-option, the matching value can have any case, upper or lower, but is always replaced by the partToHighlight-value. Instead the function should read the matched value, save it and output it surrounded with the HTML-tags. How do I do this? I am pretty sure this is a duplicate question, but I couldn't find the one asked before.

Upvotes: 2

Views: 1271

Answers (2)

cнŝdk
cнŝdk

Reputation: 32145

As mentionned in comments you will need to use RegExp.lastMatch or $&, to point out to the matched substring, in your replace() method:

const regEx = new RegExp(this.partToHighlight, 'ig');
return text.replace(regEx, `<mark>$&<\/mark>`);

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627087

You need to replace with the found match, $&:

markString(text: string) {
    const regEx = new RegExp(this.partToHighlight, 'ig');
    return text.replace(regEx, "<mark>$&</mark>");
}

Using $&, you replace with found match with the the same text found and do not need to hardcode the replacement, nor use any callbacks.

See "Specifying a string as a parameter" for more details.

Upvotes: 2

Related Questions