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

108

我有一个非常小的问题。我尝试使用concat,charAt,slice和其他方法,但我不知道如何做。

这是我的字符串:

var str1 = "Notion,Data,Identity,"
我想将最后一个,替换为.,应该看起来像这样。
var str1 = "Notion,Data,Identity."

有人能告诉我如何实现这个吗?


附带说明:https://jsperf.com/replace-last-character-of-a-string - Sylvain Leroux
4个回答

176

你可以很容易地使用正则表达式实现它,

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

.$会匹配字符串末尾的任意字符。


3
@Patrick 那是正则表达式的组成部分。.将匹配任何字符。而$会与.结合在一起,以匹配字符串末尾的任何字符。 - Rajaprabhu Aravindasamy
如果你想传递一个动态正则表达式而不是静态的,请使用 new RegExp('yourRegexString') - Rajaprabhu Aravindasamy
@RajaprabhuAravindasamy 它替换了什么? - Sayed Mohd Ali
@SayedMohdAli 使用方法如下:result = yourString.replace(new RegExp('yourRegex'), "") - Rajaprabhu Aravindasamy
没有发挥作用的表达式 = expression.replace(new RegExp('/'+expression[i]+'$/'), "")。 - Sayed Mohd Ali
显示剩余3条评论

95
您可以使用.slice(0, -N)来删除字符串的最后N个字符,并使用+将新结尾连接起来。
var str1 = "Notion,Data,Identity,";
var str2 = str1.slice(0, -1) + '.';
console.log(str2);
Notion,Data,Identity.

负索引用于切片表示从字符串末尾开始的位置,而不是从开头开始计算位置。因此,在这种情况下,我们要求获取从字符串开头到倒数第二个字符的子串。


12

这不太优雅,但是它是可重复使用的。

term(str, char)

str:需要适当终止的字符串

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,'.'))


6

您可以使用简单的正则表达式。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接