正则表达式让我很困惑。有人可以解释如何解析这个网址,以便我得到数字7
?
'/week/7'
var weekPath = window.location/path = '/week/7';
weekPath.replace(/week/,""); // trying to replace week but still left with //7/
答案 0 :(得分: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"
阅读:
答案 1 :(得分:6)
将其放在字符串而不是正则表达式
weekPath.replace("/week/","");
=> "7"
差异?
当字符串与/ /
分隔时,该字符串将被视为正则表达式模式,它将仅替换week
。
但是当" "
分隔时,它被视为原始字符串,/week/
答案 2 :(得分:4)
weekPath.replace(/week/,""); // trying to replace week but still left with //7/
在这里,您匹配了字符week
并替换了它们,但是您的模式与斜杠字符不匹配。源代码中的两个斜杠只是JavaScript中用于创建正则表达式对象的语法的一部分。
相反:
weekPath = weekPath.replace(/\/week\//, "");
答案 3 :(得分:2)
您不需要为此使用正则表达式。您只需获取路径名并将其拆分为“/”字符。
假设网址为http://localhost.com/week/7:
var path = window.location.pathname.split('/');
var num = path[1]; //7