javascript - insert a variable into regexp

前端 未结 2 1509
鱼传尺愫
鱼传尺愫 2021-01-22 05:50

I have the following which works fine, allowing a form field to be valid if blank or containing the word \"hello\" or passing the other validation...

var re = ne         


        
2条回答
  •  庸人自扰
    2021-01-22 06:05

    Drop the leading and trailing / characters and your reg exp is not going what you expect. Double up the \ characters so they are escaped. Also [] means match any of these characters.

    Basic example

    var str = "hello world";
    var word = "hello"
    var re = new RegExp("^" + word + "\\s?")
    console.log( str.match(re) );
    

提交回复
热议问题