2

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.

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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>`);

2 Comments

Actually, a more appropriate link to the $& is the one I provided in my answer, as you also provided the string replacement backreference based solution (it is the same as mine, just there is no need to escape / in the replacement pattern, as the single \ in the string literal will be removed by the engine anyway).
@WiktorStribiżew Well pointed out, thank you, I edited my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.