Javascript从字符串中删除最后一次出现的子字符串

时间:2021-03-03 11:23:52

标签: javascript

我有一个字符串 str 和一个字符串 substr

我想从 substr 中删除最后一次出现的 str

var str = "foo bar foo bar";
var substr = "foo";
str = str.removeLast(substr);

str 保留为

foo bar  bar

如何实现?

3 个答案:

答案 0 :(得分:2)

您可以使用 String.prototype.lastIndexOf() 来实现:

function removeLast(haystack, needle) {
  const idx = haystack.lastIndexOf(needle);
  return haystack.slice(0, idx) + haystack.slice(idx + needle.length);
}

注意:此函数假设 needle 始终是 haystack 的子字符串。

答案 1 :(得分:0)

试试这个:

var res = "foo bar foo bar".split(" ");
res.splice(res.reverse().findIndex(a => a === "foo"), 1);
console.log(res.reverse());

答案 2 :(得分:0)

也许这会有所帮助....

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