To replaces a particular character of string by another specific string | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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...

28th Jun 2017, 5:51 AM
ASHISH PANDEY
ASHISH PANDEY - avatar
8 Answers
+ 8
Just do var res = x.replace(/4/g, 'Z'); maybe result will be qwZrhhxZdgjZ
28th Jun 2017, 5:53 AM
김정제(Legacy)
김정제(Legacy) - avatar
+ 6
g means 'global' It replaces all mathces. If you dont use g, it will replace just one.
28th Jun 2017, 5:56 AM
김정제(Legacy)
김정제(Legacy) - avatar
+ 5
I dont think @ASHISH PANDEY wanted to replace string without new string object.
28th Jun 2017, 6:17 AM
김정제(Legacy)
김정제(Legacy) - avatar
+ 3
global modifier, its to replace all 4s without that it will only replace the first 4
28th Jun 2017, 5:56 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 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
28th Jun 2017, 6:11 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 1
why in replace function you included /g,
28th Jun 2017, 5:54 AM
ASHISH PANDEY
ASHISH PANDEY - avatar
+ 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)
28th Jun 2017, 6:02 AM
DEVENDRA VYAVAHARKAR
DEVENDRA VYAVAHARKAR - avatar
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
28th Jun 2017, 6:15 AM
DEVENDRA VYAVAHARKAR
DEVENDRA VYAVAHARKAR - avatar