0

I am a bit confused about how to do this. I have read alot about string.replace and using the RegExp object but I just can"t figure it out. I keep gettings errors or it just doesnt work. So help me out for understanding how it works in JavaScript.

I person can create a description and I want to fish out some importand words. So I started with regex and got to a point that it works like I intended, but it is only with a static word.

Example:

const value = .. <!-- the description
let tag = ..  <-- need this tag to be in the regex 

let regex = /(^|\W)abc($|\W)/; <!-- and 'abc' should be replaced with tag

if(value.match(regex)){
    // Do something
}

So how can I make the regex replace the 'abc' part with the tag variable?

Thanks already for helping.

Niels Lucas
  • 739
  • 1
  • 12
  • 31
  • `let regex = new RegExp("(^|\\W)" + tag.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "($|\\W)");` – Wiktor Stribiżew Oct 26 '18 at 09:15
  • @WiktorStribiżew Yes that worked, thank you. I have not seen this one before. I only dont know why this is working. Maybe I just need to practis more with regex. Ty – Niels Lucas Oct 26 '18 at 09:35
  • It is the same regex you have, `/(^|\W)abc($|\W)/` if `tag="abc"`. Do you understand the pattern you wrote? If not, use http://regex101.com. – Wiktor Stribiżew Oct 26 '18 at 09:36

0 Answers0