使用 JavaScript 替换字符串的最后一个字符

我有个小问题。我试过使用 concat,charAt,slice 等等,但是我不知道怎么做。

这是我的绳子:

var str1 = "Notion,Data,Identity,"

我想取代最后的 ,.它应该是这样的。

var str1 = "Notion,Data,Identity."

有人能告诉我怎么做吗?

147398 次浏览

You can do it with regex easily,

var str1 = "Notion,Data,Identity,".replace(/.$/,".")

.$ will match any character at the end of a string.

You can remove the last N characters of a string by using .slice(0, -N), and concatenate the new ending with +.

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.

This isn't elegant but it's reusable.

term(str, char)

str: string needing proper termination

char: character to terminate string with

var str1 = "Notion,Data,Identity,";


function term(str, char) {
var xStr = str.substring(0, str.length - 1);
return xStr + char;
}


console.log(term(str1,'.'))

You can use simple regular expression

var str1 = "Notion,Data,Identity,"
str1.replace(/,$/,".")