我正在使用一个 Google API,它以以下格式返回 ID,我已将其保存为字符串。如何在 javascript 中编写正则表达式以将字符串修剪为仅 URL 中最后一个斜杠之后的字符。
var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9'
我正在使用一个 Google API,它以以下格式返回 ID,我已将其保存为字符串。如何在 javascript 中编写正则表达式以将字符串修剪为仅 URL 中最后一个斜杠之后的字符。
var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9'
不要写正则表达式!这与字符串函数无关:
var final = id.substr(id.lastIndexOf('/') + 1);
如果您知道最后一部分将始终是 16 个字符,那就更容易了:
var final = id.substr(-16);
一种稍微不同的正则表达式方法:
var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];
分解这个正则表达式:
\/ 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
所述[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);
以防万一其他人遇到此线程并正在寻找一个简单的 JS 解决方案:
id.split('/').pop(-1)
这很容易理解 (?!.*/).+
让我解释:
首先,让我们匹配末尾有斜杠的所有内容,好吗? 那是我们不想要的部分
.*/
匹配所有内容直到最后一个斜线
然后,我们做一个“负前瞻”(?!)
说“我不想要这个,丢弃它”
(?!.*)
这是“负前瞻”
现在,我们可以愉快地采取一切是旁边什么我们不希望这个
.+
你可能需要逃避 / 所以它变成:
(?!.*\/).+
这个正则表达式:[^\/]+$
- 像冠军一样工作:
var id = ".../base/nabb80191e23b7d9"
result = id.match(/[^\/]+$/)[0];
// results -> "nabb80191e23b7d9"