简体   繁体   中英

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 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.

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

You can simply use lastIndexOf method of String

 var input = "Opportunity >> Source = Email >> Status = New >> Branch = Mumbai"; console.log( input.substring(0, input.lastIndexOf( ">>" )) ) 

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

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

You can splice it off:

var arr = test.split(">>");
arr = arr.splice(arr.length - 1, 1);
string = test.join(">>");

One more option: use pop()

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

var arr = src.split(">>");
arr.pop();
var s = arr.join(">>");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM