Malted
Malted

Reputation: 88

Javascript remove last occurance of substring from string

I have a string str and a string substr.

I want to remove the last occurance of substr from str.

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

to leave str as

foo bar  bar

How can this be achieved?

Upvotes: 0

Views: 54

Answers (3)

Ajinkya
Ajinkya

Reputation: 57

May be this can help....

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

Upvotes: 0

Kurt Van den Branden
Kurt Van den Branden

Reputation: 12973

Try this out:

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

Upvotes: 0

D. Pardal
D. Pardal

Reputation: 6597

You can use String.prototype.lastIndexOf() to achieve this:

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

Note: This function assumes that needle is always a substring of haystack.

Upvotes: 2

Related Questions