console.log("url/page/value".match(/\/([a-zA-Z0-9]+)/g));
Why this code return an array: [/page, /value]? Why captured symbol '/'?
jsfiddle: http://jsfiddle.net/wq93T/
Thanks in advance.
Because
\\/
in your regex means: match the literal character /
(the forward slash has to be escaped by a backslash because it is also the /pattern delimiter/
) g
modifier makes you return all matches Taken together, the regex \\/([a-zA-Z0-9]+)
means:
/
So this will match /somethingLikeThis
You can see that clearly in this demo , and experiment by adding strings to see what matches, or by editing the regex.
您使用\\
转义/
尝试使用此方法,即\\/
表示/
console.log("url/page/value".match(/([a-zA-Z0-9]+)/g));
var path = "url/page/value";
var regex = /\/([a-zA-Z0-9]+)/g;
var match = regex.exec(path);
console.log(match[0]); // "/page"
console.log(match[1]); // "page"
match = regex.exec(path);
console.log(match[0]); // "/value"
console.log(match[1]); // "value"
match = regex.exec(path);
console.log(match); //null
The array returned by exec
contains the entire match in index 0, and captures (values in parenthesis) at subsequent indices (first at 1, second at 2, etc).
As a single line:
console.log(/\/([a-zA-Z0-9]+)/g.exec("url/page/value")[1]); // "page"
As a function that returns an array of captures:
var path = "url/page/value";
var regex = /\/([a-zA-Z0-9]+)/g;
console.log(capturedMatch(path, regex, 1));
function capturedMatch(str, rgx, index) {
var m;
var res = [];
while((m = rgx.exec(str)) != null) {
res.push(m[index]);
}
return res;
}
The expression can be further simplified, if you do not want the /
, to:
console.log("url/page/value".match(/[a-zA-Z0-9]+/g));
Or
console.log("url/page/value".match(/[^\/]+/g));
Or
console.log("url/page/value".split('/'));
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.