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 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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With