Javascript/jQuery - 替换字符串中最后一次出现的单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15639102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript/jQuery - replace last occurence of a word in a string
提问by ojek
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
.
我有一个以固定单词 - 结尾的字符串Button
。现在我需要用''
. 我该怎么做?另外,如果我的字符串类似ButtonButton
或类似,我只需要剪掉最后一个Button
.
回答by Jo?o Silva
var original = 'ButtonButton';
var newString = original.replace(/Button$/, '');
// "Button"
回答by hjpotter92
回答by Wulf
If you don't have to check, if it really ends with Button
, just remove the last 6 letters:
如果您不必检查,如果它真的以 结尾Button
,只需删除最后 6 个字母:
var str = "ButtonButton";
str = str.substr(0,str.length-6);
console.log(str); //"Button"