Skip to content
Advertisement

How to remove everything that occurs after the last occurrence of a character in JavaScript? [closed]

For example, I have a string

“A – B – C asdas K – A,B,C”

Let the character be “-“

I want to save everything before the last occurrence of “-” so “A – B – C asdas K ” should be saved.

I have tried this:

str = str.split(":").pop();

How can I do this?

Advertisement

Answer

You can do something like this:

var str = "A - B - C asdas K - A,B,C";
console.log(str.substring(0, str.lastIndexOf("-")));

Firstly, you get the last index of the char that interest you: ‘-‘, then you are using substring which get 0-X string.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement