简体   繁体   中英

Regexp not matching digits in “1 1” JavaScript

This is probably a silly mistake, but I can't figure out why this isn't working

var patt = new RegExp("\s[A-Za-z0-9]");
var filtering = patt.test("1 1");
console.log(filtering);

I get false from filtering , but from my understanding filtering should be true

This:

var patt = new RegExp("\s[A-Za-z0-9]");

… creates the following regular expression:

/s[A-Za-z0-9]/

Note that there's no backslash ( \\ ) before the s , because a backslash in a string expression has to be escaped (with another backslash).

Fix that, and you'll get true as expected:

 var patt = new RegExp("\\\\s[A-Za-z0-9]"); var filtering = patt.test("1 1"); console.log(filtering); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM