简体   繁体   中英

How to remove everything after particular character

I have a string which is as below :

Documents for 047-428583 > FOLDER A > FOLDER D

I want to remove > FOLDER D while doing a particular operation.

I have tried using substring which is as below but it removes everything after >

 var data = $("#extend").text();
 $("#extend").text(data.substring(0, data.indexOf('>')));

I have gone through this but in my case i have multiple same characters so i can not use that. I guess!

Use lastIndexOf instead:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf

$("#extend").text(data.substring(0, data.lastIndexOf('>') - 1));

You could split the text() value by the > character and then remove the final element in the resulting array:

$("#extend").text(function(i, val) {
    var arr = val.split('>');
    arr.pop();
    return arr.join(' > ');
});

Example fiddle

You can split and then join again:

 var data = $("#extend").text().split('>').pop();
 data.join(" > ");

EDIT

As the comment said, pop() method returns the final string and this code is no correct. The correct answer is that @Rory McCrossan writes: https://stackoverflow.com/a/31674474/5035890

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