简体   繁体   中英

Javascript/jQuery - replace last occurence of a word in a string

I have a string that ends with a fixed word - Button . Now I need to replace that word with '' . How can I do it? Also, if my string is something like ButtonButton or similar, I need to cut out only last Button .

var original = 'ButtonButton';
var newString = original.replace(/Button$/, '');
// "Button"
var str = "you string with button";
var newstring = str.replace(/button$/i, '');

Read about replace()

If you don't have to check, if it really ends with Button , just remove the last 6 letters:

var str = "ButtonButton"; 
str = str.substr(0,str.length-6); 
console.log(str); //"Button"

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