1

I have this code from this post where it change the value of a string except html tags.

const regEx = new RegExp("(" + searchWord + ")(?!([^<]+)?>)";
 //new RegExp(`/^(${searchString})(?!([^<]+)?>)/`, 'gi'); 
setContent(content_?.replace(regEx, `<mark>${searchString}</mark>`)); //using React

but my problem is it changes all the string even at the middle of the words. Is it possible to just change the string if it the searchString only starts with it.

Example if I search the string 'age':

Wrong Scenario 1(usage):

  const sample1 = '<span>usage</span>' 
    // WRONG Result '<span>us<mark>age</mark></span>' 

usage should not be changed since it doesn't start with 'age'.

Correct Scenario 2 (agencies):

   const sample2 = '<span>agencies</span>';
  // CORRECT Result '<span><mark>age</mark>ncies</span>'  
ajbee
  • 3,511
  • 3
  • 29
  • 56
  • Do you have `const regEx = /^(${searchString})(?!([^<]+)?>)/gi;`? ``new RegExp(`/^(${searchString})(?!([^<]+)?>)/`, 'gi')`` cannot do much since there are slashes at the start and end. – Wiktor Stribiżew Apr 14 '21 at 07:55
  • When you create a regexp with `new Regexp()` you should not have slashes `/` in the string. – Poul Bak Apr 14 '21 at 08:01
  • @WiktorStribiżew not working :( – ajbee Apr 14 '21 at 08:08
  • Since you ask about how to match a *whole word* at the string start, you need to use `^` where you have it and add `\b` word boundary: ``RegExp("^(" + searchWord + ")\\b(?!([^<]+)?>)", "gi")``. The point is: you need a [word boundary](https://stackoverflow.com/questions/1324676/what-is-a-word-boundary-in-regex-does-b-match-hyphen). Also, I think the replacement must be ``"$&"`` if you want to replace with the word found in its exact case. – Wiktor Stribiżew Apr 14 '21 at 08:09
  • I'm not sure if there's a typo somewhere: const regEx = new RegExp('^(' + searchString + ')\\b(?!([^<]+)?>)', 'gi'); – ajbee Apr 14 '21 at 08:14
  • 1
    I do not think so, but I see there is some problem with the issue statement. Please check [this fiddle](https://jsfiddle.net/wiktor_stribizew/7zvocnm4/). Correct it if it is wrong and share a link. – Wiktor Stribiżew Apr 14 '21 at 08:19
  • All good now :) Thank you very much – ajbee Apr 14 '21 at 08:21
  • So, the issue was that you used a `^`, start of string anchor, instead of a `\b`, a word boundary. – Wiktor Stribiżew Apr 14 '21 at 08:24

1 Answers1

-1

You can do it like this:

let searchString = "agencies";
const regEx = new RegExp(/^age/, 'gm');

let newstr = searchString.replace(regEx, `<mark>${searchString}</mark>`)
console.log(newstr)

Output: <mark>agent</mark>

PS: It is simple JavaScript based implementation, can be applied in react too.

halfer
  • 19,824
  • 17
  • 99
  • 186
Amulya Kashyap
  • 2,333
  • 17
  • 25
  • yeah but the regex for excluding it inside html tags are excluded and also the string 'age' is hardcoded – ajbee Apr 14 '21 at 08:01