Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing character at a particular index with a string in 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 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"

like image 685
Bobby Francis Joseph Avatar asked May 28 '12 12:05

Bobby Francis Joseph


People also ask

How do you replace a character in a string at a specific index?

Like StringBuilder, the StringBuffer class has a predefined method for this purpose – setCharAt(). Replace the character at the specific index by calling this method and passing the character and the index as the parameter.

How do I replace a string at a particular index in JavaScript?

The first method is by using the substr() method. And in the second method, we will convert the string to an array and replace the character at the index. Both methods are described below: Using the substr() method: The substr() method is used to extract a sub-string from a given starting index to another index.

How do you replace a specific character in a string?

The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.

How do you replace a word in a string with the index?

You can replace multiple characters in the given string with the new character using the string indexes. For this approach, you can make use of for loop to iterate through a string and find the given indexes. Later, the slicing method is used to replace the old character with the new character and get the final output.


2 Answers

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.

like image 177
Alnitak Avatar answered Sep 29 '22 04:09

Alnitak


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
like image 39
Tom Avatar answered Sep 29 '22 02:09

Tom