Replacing character at a particular index with a string in Javascript , Jquery

▼魔方 西西 提交于 2019-12-07 05:28:29

问题


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 want to replace character at 7 with the string "wom" (regardless of what the original character was).

The final result should be : "I am a woman"


回答1:


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);
}

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.




回答2:


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



回答3:


There is a string.replace() method in 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.



来源:https://stackoverflow.com/questions/10784637/replacing-character-at-a-particular-index-with-a-string-in-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!