Variables in regexp

This question already has an answer here:

  • passing variable to a regexp in javascript [duplicate] 4 answers
  • How do you use a variable in a regular expression? 16 answers

  • var args = ['Name', 'Surname', 'City', 'Dog'];
    var regExp = new RegExp(args.join("|"));
    
    if (regExp.test(names)) {
      alert('true');
    }
    

    More generally, you just need to concatenate the arguments as a string inside a new RegExp object. Depending on what is in the variables, you may need to escape them first - but there are ample places on StackOverflow to find regular expression escaping advice.

    链接地址: http://www.djcxy.com/p/76836.html

    上一篇: 如何在javascript中将变量传递给split()

    下一篇: 正则表达式中的变量