使用 JavaScript 替换字符串的最后一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36630230/
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
Replace last character of string using JavaScript
提问by Patrick
I have a very small query. I tried using concat, charAt, slice and whatnot but I didn't get how to do it.
我有一个非常小的查询。我尝试使用 concat、charAt、slice 和诸如此类的东西,但我不知道该怎么做。
Here is my string:
这是我的字符串:
var str1 = "Notion,Data,Identity,"
I want to replace the last ,
with a .
it should look like this.
我想,
用一个.
它应该看起来像这样替换最后一个。
var str1 = "Notion,Data,Identity."
Can someone let me know how to achieve this?
有人可以让我知道如何实现这一目标吗?
回答by Rajaprabhu Aravindasamy
You can do it with regex easily,
您可以使用正则表达式轻松完成,
var str1 = "Notion,Data,Identity,".replace(/.$/,".")
.$
will match any character at the end of a string.
.$
将匹配字符串末尾的任何字符。
回答by Facebook Staff are Complicit
You can remove the last N characters of a string by using .slice(0, -N)
, and concatenate the new ending with +
.
您可以使用 删除字符串的最后 N 个字符.slice(0, -N)
,并使用连接新的结尾+
。
var str1 = "Notion,Data,Identity,";
var str2 = str1.slice(0, -1) + '.';
console.log(str2);
Notion,Data,Identity.
Negative arguments to slice represents offsets from the end of the string, instead of the beginning, so in this case we're asking for the slice of the string from the beginning to one-character-from-the-end.
slice 的负参数表示从字符串末尾而不是开头的偏移量,因此在这种情况下,我们要求字符串的切片从开头到一个字符的结尾。
回答by zer00ne
This isn't elegant but it's reusable.
这并不优雅,但它是可重用的。
term(str, char)
term(str, char)
str:
string needing proper termination
str:
需要正确终止的字符串
char:
character to terminate string with
char:
终止字符串的字符
var str1 = "Notion,Data,Identity,";
function term(str, char) {
var xStr = str.substring(0, str.length - 1);
return xStr + char;
}
console.log(term(str1,'.'))