我正在使用一个 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);
Just in case someone else comes across this thread and is looking for a simple JS solution:
id.split('/').pop(-1)
this is easy to understand (?!.*/).+
let me explain:
first, lets match everything that has a slash at the end, ok? that's the part we don't want
.*/
matches everything until the last slash
then, we make a "Negative lookahead" (?!)
to say "I don't want this, discard it"
(?!.*)
this is "Negative lookahead"
Now we can happily take whatever is next to what we don't want with this
.+
YOU MAY NEED TO ESCAPE THE / SO IT BECOMES:
(?!.*\/).+
这个正则表达式:[^\/]+$
- 像冠军一样工作:
var id = ".../base/nabb80191e23b7d9"
result = id.match(/[^\/]+$/)[0];
// results -> "nabb80191e23b7d9"
这应该有效:
last = id.match(/\/([^/]*)$/)[1];
//=> nabb80191e23b7d9
不了解 JS,使用其他示例(和猜测)-
id = id.match(/[^\/]*$/);
// [0] 可选的?
为什么不使用替换?
"http://google.com/aaa".replace(/(.*\/)*/,"")
产生“aaa”