57

我正在使用一个 Google API,它以以下格式返回 ID,我已将其保存为字符串。如何在 javascript 中编写正则表达式以将字符串修剪为仅 URL 中最后一个斜杠之后的字符。

var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9'
4

8 回答 8

93

不要写正则表达式!这对于字符串函数来说是微不足道的:

var final = id.substr(id.lastIndexOf('/') + 1);

如果您知道最后部分总是 16 个字符,那就更容易了:

var final = id.substr(-16);
于 2013-11-04T21:00:08.103 回答
52

稍微不同的正则表达式方法:

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);

于 2013-11-04T21:02:58.833 回答
26

Just in case someone else comes across this thread and is looking for a simple JS solution:

id.split('/').pop(-1)

于 2015-01-20T21:12:26.330 回答
25

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:

(?!.*\/).+

于 2016-02-22T06:56:19.957 回答
13

这个正则表达式:[^\/]+$- 像冠军一样工作:

var id = ".../base/nabb80191e23b7d9"

result = id.match(/[^\/]+$/)[0];

// results -> "nabb80191e23b7d9"
于 2017-12-22T22:26:36.177 回答
9

这应该有效:

last = id.match(/\/([^/]*)$/)[1];
//=> nabb80191e23b7d9
于 2013-11-04T20:59:24.953 回答
7

不了解 JS,使用其他示例(和猜测)-

id = id.match(/[^\/]*$/);// [0] 可选的?

于 2013-11-04T21:20:04.833 回答
3

为什么不使用替换?

"http://google.com/aaa".replace(/(.*\/)*/,"")

产生“aaa”

于 2019-02-07T12:16:49.483 回答