我正在使用以下格式返回ID的Google API,我将其保存为字符串.如何在javascript中编写正则表达式以将字符串修剪为仅在URL中的最后一个斜杠之后的字符.
var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9'
Run Code Online (Sandbox Code Playgroud)
lon*_*day 77
不写正则表达式!这对于字符串函数来说是微不足道的:
var final = id.substr(id.lastIndexOf('/') + 1);
Run Code Online (Sandbox Code Playgroud)
如果你知道最终部分总是16个字符,那就更容易了:
var final = id.substr(-16);
Run Code Online (Sandbox Code Playgroud)
jfr*_*d00 43
一种略有不同的正则表达式方法:
var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];
Run Code Online (Sandbox Code Playgroud)
打破这个正则表达式:
\/ match a slash
( start of a captured group within the match
[^\/] match a non-slash character
+ match one of more of the non-slash characters
) end of the captured group
\/? allow one optional / at the end of the string
$ match to the end of the string
Run Code Online (Sandbox Code Playgroud)
所述[1]然后检索匹配内的第一捕获组
工作片段:
var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9';
var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];
// display result
document.write(afterSlashChars);Run Code Online (Sandbox Code Playgroud)
小智 15
以防其他人遇到这个帖子并且正在寻找一个简单的JS解决方案:
id.split( '/').弹出(-1)
lal*_*alo 10
这很容易理解 (?!.*/).+
让我解释:
首先,让我们匹配最后有斜杠的所有东西,好吗? 这是我们不想要的部分
.*/ 匹配所有内容直到最后一个斜杠
然后,我们做出"负面的预测" (?!)来说"我不想要这个,丢弃它"
(?!.*) 这是"消极的向前看"
现在,我们可以愉快地采取一切是旁边什么我们不希望这个
.+
你可能需要逃避它/因此成为:
(?!.*\/).+
And*_*ndy 10
这个正则表达式:[^\/]+$- 像冠军一样:
var id = ".../base/nabb80191e23b7d9"
result = id.match(/[^\/]+$/)[0];
// results -> "nabb80191e23b7d9"
Run Code Online (Sandbox Code Playgroud)
这应该工作:
last = id.match(/\/([^/]*)$/)[1];
//=> nabb80191e23b7d9
Run Code Online (Sandbox Code Playgroud)