Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does javascript have a method to replace part of a string without creating a new string?

var str = "This is a string"; var thing = str.replace("string","thing");  console.log( str ) >> "This is a string"   console.log( thing ) >> "This is a thing"  

Is there another method I can use, besides replace, that will alter the string in place without giving me a new string object?

like image 894
djacobs7 Avatar asked May 31 '11 18:05

djacobs7


People also ask

How do you replace a certain part of a string JavaScript?

replace() is an inbuilt method in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged. Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.

How do you replace a specific part of 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 character in a string in JavaScript without using replace method?

To replace a character in a String, without using the replace() method, try the below logic. Let's say the following is our string. int pos = 7; char rep = 'p'; String res = str. substring(0, pos) + rep + str.


2 Answers

No, strings in JavaScript are immutable.

like image 158
Cristian Sanchez Avatar answered Sep 25 '22 17:09

Cristian Sanchez


Not that i am aware of, however if the reason you want to do this is just to keep your code clean you can just assign the new string the the old variable:

var string = "This is a string"; string = string.replace("string", "thing"); 

Of course this will just make the code look a bit cleaner and still create a new string.

like image 26
Jan-Peter Vos Avatar answered Sep 25 '22 17:09

Jan-Peter Vos