使用正则表达式解析这个字符串?

3

对我来说,正则表达式太令人困惑了。有人能解释一下如何解析这个URL,以便我只获取数字7吗?

'/week/7'

var weekPath = window.location/path = '/week/7';
weekPath.replace(/week/,""); // trying to replace week but still left with //7/

'/week/7'.split('/')[2] - anubhava
4个回答

6

修复你的正则表达式:

\/添加到你的正则表达式中,如下所示。这将捕获字符串week前后的/

var weekPath = '/week/7';
var newString = weekPath.replace(/\/week\//,"");

console.dir(newString); // "7"

Alternative solution with .match():

To grab just the number at the end of the string with regex:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接