Javascript 用Javascript中的字符串替换特定索引处的字符,Jquery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10784637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replacing character at a particular index with a string in Javascript , Jquery
提问by Bobby Francis Joseph
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"
假设有一个字符串: "I am a man"
I want to replace character at 7 with the string "wom"
(regardless of what the original character was).
我想用字符串替换 7 处的字符"wom"
(无论原始字符是什么)。
The final result should be : "I am a woman"
最终结果应该是: "I am a woman"
回答by Alnitak
Strings are immutablein Javascript - you can't modify them "in place".
字符串在 Javascript 中是不可变的——你不能“就地”修改它们。
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);
}
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.
注意:我没有添加它,String.prototype
因为在某些浏览器上,如果向prototype
内置类型添加函数,性能会很差。
回答by Tom
Or you could do it this way, using array functions.
或者你可以这样做,使用数组函数。
var a='I am a man'.split('');
a.splice.apply(a,[7,1].concat('wom'.split('')));
console.log(a.join(''));//<-- I am a woman
回答by Slavo
There is a string.replace()
method in Javascript:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
string.replace()
Javascript 中有一个方法:https:
//developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
P.S.
By the way, in your first example, the index of the "m" you are talking about is 7. Javascript uses 0-based indices.
PS
顺便说一下,在你的第一个例子中,你正在谈论的“m”的索引是 7。Javascript 使用基于 0 的索引。