正则表达式让我很困惑.有人可以解释如何解析这个网址,以便我得到这个数字7
吗?
'/week/7' var weekPath = window.location/path = '/week/7'; weekPath.replace(/week/,""); // trying to replace week but still left with //7/
Rahul Desai.. 6
修复你的正则表达式:
添加\/
到你的正则表达式如下.这将捕获/
字符串之前和之后week
.
var weekPath = '/week/7';
var newString = weekPath.replace(/\/week\//,"");
console.dir(newString); // "7"
.match()
:
var weekPath = '/week/7';
var myNumber = weekPath.match(/\d+$/);// \d captures a number and + is for capturing 1 or more occurrences of the numbers
console.dir(myNumber[0]); // "7"
阅读:
String.prototype.replace()
- JavaScript | MDN
String.prototype.match()
- JavaScript | MDN
nu11p01n73R.. 6
把它放在字符串而不是正则表达式
weekPath.replace("/week/",""); => "7"
区别 ?
当字符串与其分隔时/ /
,该字符串将被视为正则表达式模式,该模式仅替换week
为您.
但是当分隔时" "
,它被视为原始字符串,/week/
修复你的正则表达式:
添加\/
到你的正则表达式如下.这将捕获/
字符串之前和之后week
.
var weekPath = '/week/7';
var newString = weekPath.replace(/\/week\//,"");
console.dir(newString); // "7"
把它放在字符串而不是正则表达式
weekPath.replace("/week/",""); => "7"
区别 ?
当字符串与其分隔时/ /
,该字符串将被视为正则表达式模式,该模式仅替换week
为您.
但是当分隔时" "
,它被视为原始字符串,/week/