ojek
ojek

Reputation: 10088

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.

Upvotes: 5

Views: 11020

Answers (3)

Wulf
Wulf

Reputation: 3898

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"

Upvotes: 1

hjpotter92
hjpotter92

Reputation: 80653

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

Read about replace()

Upvotes: 1

João Silva
João Silva

Reputation: 91369

var original = 'ButtonButton';
var newString = original.replace(/Button$/, '');
// "Button"

Upvotes: 12

Related Questions