1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Passing a variable into a JavaScript RegExp method

Discussion in 'JavaScript' started by Alex100, Aug 21, 2020.

  1. #1
    How can I pass a variable into a JavaScript RegExp match method?
    SEMrush
    I have this code:

    
    let rgx = new RegExp(/(?<= )(word1|word2|word3)(?= )/).source;
    Code (markup):
    What I'd like to do is store 'word1|word2|word3' in a variable, and then integrate it in the code above. I searched Google and tried in multiple ways, but nothing seems to work. As a quick example, the following code doesn't work...

    
    let regex_variable = "word1|word2|word3";
    let rgx = new RegExp("/(?<= )(" + regex_variable + ")(?= )/").source;
    Code (markup):
    Thank you,

    Alex
     
    Alex100, Aug 21, 2020 IP
    SEMrush
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,530
    Likes Received:
    1,934
    Best Answers:
    247
    Trophy Points:
    515
    #2
    ).source;

    Do you see the problem here? You're pulling the string value of it, instead of the actual regexp object.
     
    deathshadow, Aug 21, 2020 IP
  3. Alex100

    Alex100 Greenhorn

    Messages:
    12
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #3
    Yes, because I'm using this code format...

    let rgx1 = new RegExp(/(?<= )(word1|word2|word3)(?= )/).source;
    let rgx2 = new RegExp(/(additional regular expressions here)/).source;
    let rgx3 = new RegExp(/(additional regular expressions here)/).source;
    
    let final_regex = new RegExp(rgx1 + "|" + rgx2 + "|" + rgx3,'gi');
    Code (markup):
    I only listed three regular expressions above, but I have around twenty, and this kind of approach enables me to keep everything organized and easy to follow.

    Right now I'm looking for a way to use variables inside the RegExp methods above. This would add flexibility and simplify things even more.

    What's the best way to do this, while keeping the format listed above?

    Sorry, my JS experience is very limited. I'm using this with a script that highlights keywords on web pages.

    Alex
     
    Alex100, Aug 21, 2020 IP
  4. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,530
    Likes Received:
    1,934
    Best Answers:
    247
    Trophy Points:
    515
    #4
    I don't think you can "or" (|) between /exp/ in JS.

    Though I'm hoping this is server-side code... because if your client-side code is getting that convoluted with the regex, something is SERIOUSLY wrong with either the data, or how the server is handling it.
     
    deathshadow, Aug 21, 2020 IP