[英]If a string after the last slash of a URL exists, capture the value; if not, capture the value before the last slash (javascript)
[英]Regex to capture entire string after second instance of a slash
我有一个采用路径形式的字符串,例如:
Year 1 / English / Writing / How to write your name
我需要生成一个字符串,这是第二个正斜杠后的所有内容。 从上面的例子来看,这意味着我想要的输出是:
Writing / How to write your name
我已经看到了一些关于输出URL的最后部分或在文件路径中获取特定文件夹名称的问题/答案,但到目前为止它们都没有对我有用。 我承认由于时间限制,我的研究并不广泛。
我的第一个想法是在javascript中执行以下操作:
var input = "Year 1 / English / Writing / How to write your name";
var firstCut = input.substr(input.indexOf('/') + 1);
var secondCut = firstCut.substr(firstCut.indexOf('/') + 1);
我更喜欢更优雅的解决方案,如果可能的话,最好使用正则表达式!
谢谢
您可以使用replace
方法:
var s = "Year 1 / English / Writing / How to write your name"; var result = s.replace(/^(?:[^\\/]*\\/){2}\\s*/, ''); console.log(result);
模式将匹配(和.replace
最终将删除它):
^
- 字符串的开头 (?:[^\\/]*\\/){2}
- 两次出现
[^\\/]*
- 除了/
0+字符 \\/
- a /
char \\s*
- 0+空格 如果没有匹配,则结果将等于输入字符串。
匹配的方法可能看起来像
var s = "Year 1 / English / Writing / How to write your name"; var result = (m = s.match(/^(?:[^\\/]*\\/){2}\\s*([\\s\\S]+)/)) ? m[1] : ""; console.log(result);
在初始文本与上述模式匹配之后 , ([\\s\\S]+)
模式将捕获到组1中的任何一个或多个字符,直到字符串结尾。
如果没有匹配,结果将是一个空字符串。
此正则表达式将以[entire string match, captured group]
的形式返回一个数组。 它从字符串的开头开始,匹配两组任意数量的字符,这些字符不是/
后跟/
,然后从那里捕获其余字符到字符串的末尾。
let test = "Year 1 / English / Writing / How to write your name" let result = /^(?:[^\\/]+\\/){2}(.+)/.exec(test)[1] console.log(result)
也就是说,最好的答案可能是使用split
和join
:
let test = "Year 1 / English / Writing / How to write your name" let result = test.split(/\\s*\\/\\s*/).slice(2).join(" / ") console.log(result)
您可以使用^.*?\\/.*?\\/
删除您不想要的部分。
防爆。
var string = 'Year 1 / English / Writing / How to write your name'; var result = string.replace(/^.*?\\/.*?\\//, ''); console.log(result);
如果你想捕获组使用^.*?\\/.*?\\/(.*)$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.