一个特定的指数在一个字符串在Javascript,jQuery的更换角色在一、字符串、角色、指数

由网友(渡我这苦海)分享简介:是否有可能取代一个字符一个字符串中的特定位置Is it possible to replace the a character at a particular position with a string 让我们说有说的字符串:我一个人 Let us say there is say a string : "I...

是否有可能取代一个字符一个字符串中的特定位置

Is it possible to replace the a character at a particular position with a string

让我们说有说的字符串:我一个人

Let us say there is say a string : "I am a man"

我想在7字符串WOM替换字符(无论什么样的原始字符是)。

I want to replace character at 7 with the string "wom" (regardless of what the original character was).

最后的结果应该是:我是女人

推荐答案

字符串是的一成不变的在Javascript中 - 你不能到位进行修改

Strings are immutable in Javascript - you can't modify them "in place".

您将需要削减原始字符串起来,并返回做出来的所有的作品的一个新的字符串:

You'll need to cut the original string up, and return a new string made out of all of the pieces:

// 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 ,因为在某些浏览器,如果你将函数添加到表现非常糟糕原型

NB: I didn't add this to String.prototype because on some browsers performance is very bad if you add functions to the prototype of built-in types.