最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin8浏览0评论

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"

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"

Share Improve this question edited May 28, 2012 at 12:47 Alnitak 340k71 gold badges418 silver badges502 bronze badges asked May 28, 2012 at 12:25 Bobby Francis JosephBobby Francis Joseph 6002 gold badges15 silver badges34 bronze badges 3
  • 1 See also here stackoverflow.com/questions/1431094/… (you can use the function of the selected answer, works as well for strings). – ixx Commented May 28, 2012 at 12:30
  • @lxx no, that function is no good as it replaces as many characters in the source string as were supplied - the OP here only wants one character replaced. – Alnitak Commented May 28, 2012 at 12:45
  • Does this answer your question? How do I replace a character at a particular index in JavaScript? – wesinat0r Commented Dec 31, 2019 at 4:34
Add a comment  | 

3 Answers 3

Reset to default 22

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.

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

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.

发布评论

评论列表(0)

  1. 暂无评论