好的,我有这个
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
console.log(URL.substring(URL.lastIndexOf("/")));给你"/remove-everything-before-the-last-occurrence-of-a-character“
怎样才能得到"http://stackoverflow.com/questions/10767815/“
发布于 2015-07-09 04:46:02
给你:
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
alert(URL.substring(0, URL.lastIndexOf("/") + 1));
希望这能有所帮助。
发布于 2015-07-09 04:56:39
对于正则表达式来说,这似乎是一个很好的例子(不敢相信还没有人发布):
URL.replace(/[^\/]+$/,'')将所有连续的非正向斜杠字符移除到字符串的末尾(即最后/之后的所有内容)。
发布于 2020-12-01 22:12:51
通用解决方案
这是一个通用函数,当我们正在搜索的字符串中找不到搜索的字符或字符串(指针)时,它也处理边缘情况。在这种情况下,它返回原始字符串。
function trimStringAfter(haystack, needle) {
const lastIndex = haystack.lastIndexOf(needle)
return haystack.substring(0, lastIndex === -1 ? haystack.length : lastIndex + 1)
}
console.log(trimStringAfter('abcd/abcd/efg/ggfbf', '/')) // abcd/abcd/efg/
console.log(trimStringAfter('abcd/abcd/abcd', '/')) // abcd/abcd/
console.log(trimStringAfter('abcd/abcd/', '/')) // abcd/abcd/
console.log(trimStringAfter('abcd/abcd', '/')) // abcd/
console.log(trimStringAfter('abcd', '/')) // abcd
https://stackoverflow.com/questions/31308281
复制相似问题