如何使用正则表达式在字符串的倒数第二个索引中插入特定字符



我想在字符串的倒数第二个索引中插入一个连字符-

我使用substring()在javascript中创建了一个代码:

let str = "mystring";
let size = str.length;
let lastCaracter = str.substring(size - 1, size);
let newStr = str.substring(0, size - 1);
newStr = newStr + "-" + lastCaracter;

但我认为正则表达式更干净,那么如何将此代码转换为正则表达式?

这里有几个方法,有正则表达式,有正则表达式,有正则表达式。我不确定我是否同意正则表达式更干净,所以我会把它留给你。

话虽如此,用let size = str.length;缓存长度是一种有问题的做法。只需直接访问.length,这消除了对size引用内容的混淆,并避免了变量长度更改但您忘记更新缓存副本时的错误。

const str = "mystring";
const hyphenated = `${str.slice(0, -1)}-${str.slice(-1)}`;
console.log(hyphenated);

const str = "mystring";
const hyphenated = str.replace(/(.)$/, "-$1");
console.log(hyphenated);

w将捕获任何单词字符,$选择该选择末尾的位置

$1是对我们在正则表达式中选择的反向引用,我们在此之前添加一个-

console.log("myString".replace(/(w)$/, "-$1"))

最新更新