用Javascript,Jquery中的字符串替换特定索引处的字符

是否可以用字符串替换特定位置的字符

让我们说有一个字符串: "I am a man"

我想用字符串"wom"替换7处的字符(无论原始字符是什么)。

最终的结果应该是: "I am a woman"

字符串在Javascript中是不可变的 – 您无法“就地”修改它们。

您需要剪切原始字符串,并返回由所有部分组成的新字符串:

 // replace the 'n'th character of 's' with 't' function replaceAt(s, n, t) { return s.substring(0, n) + t + s.substring(n + 1); } 

注意:我没有将它添加到String.prototype因为在某些浏览器中,如果向内置类型的prototype添加函数,性能会非常糟糕。

或者你可以这样做,使用数组函数。

 var a='I am a man'.split(''); a.splice.apply(a,[7,1].concat('wom'.split(''))); console.log(a.join(''));//<-- I am a woman 

Javascript中有一个string.replace()方法: https : //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

PS
顺便说一下,在你的第一个例子中,你所谈论的“m”的索引是7.Javascript使用从0开始的索引。

Interesting Posts