+ 4
To replaces a particular character of string by another specific string
var x = "qw4rhhx4dgj4" I want to replace 4, with alphabet Z, how to do...
8 Réponses
+ 8
Just do
var res = x.replace(/4/g, 'Z');
maybe result will be
qwZrhhxZdgjZ
+ 6
g means 'global'
It replaces all mathces.
If you dont use g, it will replace just one.
+ 5
I dont think @ASHISH PANDEY
wanted to replace string without new string object.
+ 3
global modifier, its to replace all 4s without that it will only replace the first 4
+ 2
@DEVENDRA VYAVAHARKAR
ahahaha ik what u mean yes strings are immutable like if u do str = "Hello" and u do sth like str[1] = "u" it wont change the string to Hullo. what ur saying is true but the replace prototype method actually does what u mentioned
+ 1
why in replace function you included /g,
+ 1
You cannot alter the string object itself. You'll have to create a new String object.
1) To replace a single character, convert the string into a character array, replace the required character, and convert the character array back to a string.
2) For replacing a sequence of characters, divide the original string into 3 parts using substring() method: a) the part before the sequence, b) the sequence to the altered, and c) the part after the sequence
Now create a new String Object by a) + altered string b) + c)
3) Another alternative to above options 1) & 2) is to convert the String into Stringbuilder; a Stringbuilder object can be altered unlike String Object. There's a default method replace(int start, int end, int string)
0
@cheeze
What you are saying is true, but you did create a new String object while doing this. You did not alter the same object.
Even if you have a string reference str and wish to alter it with str=str.replace(0,3,"abc") you are actually creating a new object and not altering the old one