How to pass a variable into regex in jQuery/Javascript

后端 未结 3 538
孤城傲影
孤城傲影 2020-12-07 21:57

Is there a way to pass a variable into a regex in jQuery/Javascript?

I wanna do something like:

var variable_regex = \"bar\";
var some_string = \"foo         


        
相关标签:
3条回答
  • 2020-12-07 22:36

    Javascript doesn't support interpolation like Ruby -- you have to use the RegExp constructor:

    var aString = "foobar";
    var pattern = "bar";
    
    var matches = aString.match(new RegExp(pattern));
    
    0 讨论(0)
  • 2020-12-07 22:50

    It's easy:

    var variable_regex = "bar";
    var some_string = "foobar";
    
    some_string.match(variable_regex);
    

    Just lose the //. If you want to use complex regexes, you can use string concatenation:

    var variable_regex = "b.";
    var some_string = "foobar";
    
    alert (some_string.match("f.*"+variable_regex));
    
    0 讨论(0)
  • 2020-12-07 22:57

    Another way to include a variable in a string is through string interpolation. In JavaScript, you can insert or interpolate variables in strings using model literals:

    var name = "Jack";
    var id = 123321;
    
    console.log(`Hello, ${name} your id is ${id}.`);
    

    Note: be careful not to confuse quotation marks or apostrophes for the serious accent (`).

    You can use in function:

    function myPhrase(name, id){
       return `Hello, ${name} your id is ${id}.`;
    }
    
    0 讨论(0)
提交回复
热议问题