正则表达式对我来说很困惑。有人可以解释如何解析这个网址,所以我只是得到号码7
?使用正则表达式来解析这个字符串?
'/week/7'
var weekPath = window.location/path = '/week/7';
weekPath.replace(/week/,""); // trying to replace week but still left with //7/
正则表达式对我来说很困惑。有人可以解释如何解析这个网址,所以我只是得到号码7
?使用正则表达式来解析这个字符串?
'/week/7'
var weekPath = window.location/path = '/week/7';
weekPath.replace(/week/,""); // trying to replace week but still left with //7/
修复您的正则表达式:
如下添加\/
到您的正则表达式。这将捕获字符串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"
读了起来:
把它作为字符串,而不是正则表达式
weekPath.replace("/week/","");
=> "7"
区别?
当字符串与/ /
分隔时,则该字符串将被视为正则表达式模式,它只会替代week
。
但是当" "
分隔,它被视为原始字符串,/week/
weekPath.replace(/week/,""); // trying to replace week but still left with //7/
在这里,你匹配的字符week
和更换他们,但是你的模式不匹配的斜杠字符。源代码中的两个斜线只是JavaScript中用于创建正则表达式对象的语法的一部分。
相反:
weekPath = weekPath.replace(/\/week\//, "");
你并不需要使用正则表达式这一点。你可以得到路径名并分割成'/'字符。
假定URL是http://localhost.com/week/7:
var path = window.location.pathname.split('/');
var num = path[1]; //7
' '/week/7'.split('/')[2]' – anubhava