我正在使用谷歌API,该API返回以下格式的ID,我已将其保存为字符串。如何在JavaScript中编写正则表达式以仅截取URL中最后一个斜杠之后的字符。
var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9'
我正在使用谷歌API,该API返回以下格式的ID,我已将其保存为字符串。如何在JavaScript中编写正则表达式以仅截取URL中最后一个斜杠之后的字符。
var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9'
var final = id.substring(id.lastIndexOf('/') + 1);
如果你知道最后一部分总是16个字符,那就更容易了。
var final = id.substring(id.length - 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)
(将字符串 id 按照 / 分割,并返回其中的最后一个元素)这很容易理解:(?!.*/).+
让我解释一下:
首先,让我们匹配所有以斜杠结尾的内容,好吗?那是我们不想要的部分
.*/
匹配最后一个斜杠之前的所有内容
然后,我们使用"Negative lookahead"(?!)
来表示"我不想要这个,丢弃它"
(?!.*)
就是"Negative lookahead"
现在,我们可以愉快地使用这个.+
来取出我们不想要的内容旁边的任何内容
您可能需要转义/,所以它变成了:
(?!.*\/).+
这个正则表达式:[^\/]+$
- 像冠军一样工作:
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(/(.*\/)*/,"")
substr($id, strrpos($id, "/") + 1)
。该代码意思为获取$id
中最后一个斜杠后的所有字符(不包括斜杠)。 - Jan