Reputation: 51
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 split()
, reverse()
, join()
, indexOf()
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.
Upvotes: 0
Views: 316
Reputation: 21499
You can use regex in .replace()
to removing extra part of string. Regex select last part of string (>> Branch = Mumbai
) and repalace it with empty. You can see it in demo
var text = "Opportunity >> Source = Email >> Status = New >> Branch = Mumbai";
console.log(text.replace(/>>[^>]+$/g, ""));
Upvotes: 0
Reputation: 28621
One more option: use pop()
var src = "Opportunity >> Source = Email >> Status = New >> Branch = Mumbai"
var arr = src.split(">>");
arr.pop();
var s = arr.join(">>");
Upvotes: 0
Reputation: 68433
You can simply use lastIndexOf method of String
var input = "Opportunity >> Source = Email >> Status = New >> Branch = Mumbai";
console.log( input.substring(0, input.lastIndexOf( ">>" )) )
Upvotes: 2
Reputation: 82251
You can get the lastindex of >>
and then get substring from beginning of string to last position of element >>
in it :
var str = "Opportunity >> Source = Email >> Status = New >> Branch = Mumbai"
var lastindex = str.lastIndexOf(">>");
if (lastindex != -1){
alert(str.substring(0, lastindex-1 ));
}
Upvotes: 1
Reputation: 11607
You can splice
it off:
var arr = test.split(">>");
arr = arr.splice(arr.length - 1, 1);
string = test.join(">>");
Upvotes: 0
Reputation: 4364
Javascript has lastIndexOf() method . You can find last occurance with it. Then remove rest of the string easily. Example:
var test = "Opportunity >> Source = Email >> Status = New >> Branch = Mumbai";
var finIndex = test.lastIndexOf('>>');
var string = test.substring(0, finIndex);
You can check link here
Upvotes: 0
Reputation: 10470
Please try this:
"Opportunity >> Source = Email >> Status = New >> Branch = Mumbai".split(" >> ").slice(0, -1).join(" >> ")
var str = "Opportunity >> Source = Email >> Status = New >> Branch = Mumbai";
console.log(str.split(" >> ").slice(0, -1).join(" >> "));
Upvotes: 3