[英]Javascript remove last occurance of substring from string
我有一个字符串str
和一个字符串substr
。
我想从str
中删除最后一次出现的substr
。
var str = "foo bar foo bar";
var substr = "foo";
str = str.removeLast(substr);
离开str
作为
foo bar bar
如何做到这一点?
您可以使用String.prototype.lastIndexOf()
来实现这一点:
function removeLast(haystack, needle) {
const idx = haystack.lastIndexOf(needle);
return haystack.slice(0, idx) + haystack.slice(idx + needle.length);
}
注意:此 function 假定needle
始终是haystack
的 substring 。
试试这个:
var res = "foo bar foo bar".split(" "); res.splice(res.reverse().findIndex(a => a === "foo"), 1); console.log(res.reverse());
也许这可以帮助....
var str = "foo bar foo bar"; var substr = "foo"; var sub = str.slice(0,3); str =str.replaceAll("foo ","") #console.log(str); #console.log(sub); console.log(sub+" "+str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.