Replacing a character in a specific index with a string in Javascript, jQuery

Is it possible to replace the character a in a certain place with the string

Let's say there is a line: "I am a man"

I want to replace the character with a 7 string "wom"(regardless of the source character).

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

+5
source share
3 answers

Strings are immutable in Javascript - you cannot change them "in place".

You will need to cut the original line and return a new line made from all parts:

// 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 did not add this to String.prototype, because in some browsers the performance is very poor if you add functions to the prototypebuilt-in types.

+17
source

, .

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

There is a method in Javascript string.replace(): https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

PS
By the way, in the first example, the index "m" you are talking about is 7. Javascript uses 0-based indexes.

-1
source

All Articles