正则表达式让我感到困惑。有人可以解释如何解析此网址,以便我得到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"


阅读:
  • String.prototype.replace() - JavaScript | MDN
  • String.prototype.match() - JavaScript | MDN
  • 09-17 10:22