在JavaScript中,如何实现rfind?
www.mydomain.com/invite/abc123
我想让这个函数返回“abc123”。它的逻辑是这样的:
If there is a forward slash, then take all characters after the last forward slash.
在Python中,我是这样写的:
if s.find('/') >= 0:
return s[s.rfind('/')+1:]
但是我该怎么在JavaScript中实现呢?
2 个回答
10
你可以直接这样写
s.substring(s.lastIndexOf("/"))
如果s
里面没有斜杠,就会返回整个字符串!
7
你不需要使用正则表达式来完成这个任务。
var s = "www.mydomain.com/invite/abc123";
if(s.indexOf("/")>=0)
alert(s.split("/").pop());