2015-12-21 88 views

回答

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"



要在字符串的正则表达式与年底抢刚数

读了起来:

6

把它作为字符串,而不是正则表达式

weekPath.replace("/week/",""); 
=> "7" 

区别?

当字符串与/ /分隔时,则该字符串将被视为正则表达式模式,它只会替代week

但是当" "分隔,它被视为原始字符串,/week/

4
weekPath.replace(/week/,""); // trying to replace week but still left with //7/ 

在这里,你匹配的字符week和更换他们,但是你的模式不匹配的斜杠字符。源代码中的两个斜线只是JavaScript中用于创建正则表达式对象的语法的一部分。

相反:

weekPath = weekPath.replace(/\/week\//, ""); 
2

你并不需要使用正则表达式这一点。你可以得到路径名并分割成'/'字符。

假定URL是http://localhost.com/week/7

var path = window.location.pathname.split('/'); 
var num = path[1]; //7 
相关问题