Code:
var match1 = new RegExp('\S*//weibo\.com/p/\S*');
var match2 = new RegExp('\S*//weibo\.com/p/\S+');
match1.test('http://weibo.com/p/12345/myfollow?relate=fans#place');//true
match2.test('http://weibo.com/p/12345/myfollow?relate=fans#place');//false
I’m a little confused, why match2 is false, and what the hell does match1 match?
阿神2017-05-19 10:33:59
Brother, there is something wrong with your regular expression. First of all, there are two forms of regular expression construction, one is like yours, and the other is /abc/g
.
Depending on what you mean, your regular expression should be written like this:
var match1 = new RegExp('\S*//weibo\.com/p/\S*');
var match2 = new RegExp('\S*//weibo\.com/p/\S+');
Yours is missing a backslash and the escaping fails
Why? Because according to your regular expression, actually:
var match1 = new RegExp('\S*//weibo\.com/p/\S*');
match1.source;
// "S*\/\/weibo.com\/p\/S*"
Then there is the difference of *
和 +
, so the first one is true and the second one is false.
It is recommended to use two slashes when constructing a regular expression, so that there is no need to escape:
var match1 = /\S*\/\/weibo\.com\/p\/\S/;
match1.source;
// "\S*\/\/weibo\.com\/p\/\S"
黄舟2017-05-19 10:33:59
match1: s matches 0 to 1 or more spaces. //It is best to escape this and use // so that the matched one is '/'. This matches '.', if there is no backslash The bar matches any character, and the last s matches 0 to 1 or more spaces.
match2: Only the last one is different, s+, one or more spaces, but your string obviously has no spaces after p, so it is false