Javascript Regexp dynamic generation from variables ?

Javascript Regexp dynamic generation from variables ?

Asked on January 8, 2019 in Regex.
Add Comment


  • 4 Answer(s)

    For this use RegExp :

    str.match(new RegExp(pattern1+'|'+pattern2, 'gi'));
    

    If we have a backslash in our pattern to escape a special regex character, like \(,To use two backslashes in the string because \ is the escape character in a string: new RegExp(‘\\(‘) same as /\(/.

    And output of pattern is:

    var pattern1 = ':\\(|:=\\(|:-\\(';
    var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';
    

     

    Answered on January 8, 2019.
    Add Comment

    Alternately try this code for Javascript Regexp dynamic generation from variables :

    var regEx = new RegExp(pattern1+'|'+pattern2, 'gi');
     
    str.match(regEx);
    
    Answered on January 8, 2019.
    Add Comment

    Use the object constructor will pass the regex as a string:

    var regex = new RegExp(pattern1+'|'+pattern2, 'gi');
    str.match(regex);
    
    Answered on January 8, 2019.
    Add Comment

    var str = $(“#div”).html();
    var regex = “/(?!(?:[^|[^>]+))\\b(” + value + “)\\b/is”;
    $(“#div”).html(str.replace(regex, “

    Answered on January 26, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.