user3143514 user3143514 - 1 year ago 87
jQuery Question

How to remove a specific section of a string after the last occurrence of a specific character?

I have one string

"Opportunity >> Source = Email >> Status = New >> Branch = Mumbai"

Now, I want to chop off above string from last occurrence of
. I mean, I want the result string should be like this

"Opportunity >> Source = Email >> Status = New"

Now, I am using various jquery/javascript functions like
to remove the rest of the string from the last occurrence of
, like this

var test = "Opportunity >> Source = Email >> Status = New >> Branch = Mumbai";
var count = test.split("").reverse().join("").indexOf('>>');
var string = test.substring(0, test.length - count-2);

Using this, I am able to get the desired result. But I assume there must be some other easier way than this to achieve this using jquery/javascript.

Answer Source

You can simply use lastIndexOf method of String

var input = "Opportunity >> Source = Email >> Status = New >> Branch = Mumbai";

console.log( input.substring(0, input.lastIndexOf( ">>" )) )

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download