How can I perform a str_replace in JavaScript, replacing text in JavaScript? How can I perform a str_replace in JavaScript, replacing text in JavaScript? javascript javascript

How can I perform a str_replace in JavaScript, replacing text in JavaScript?


You would use the replace method:

text = text.replace('old', 'new');

The first argument is what you're looking for, obviously. It can also accept regular expressions.

Just remember that it does not change the original string. It only returns the new value.


More simply:

city_name=city_name.replace(/ /gi,'_');

Replaces all spaces with '_'!


All these methods don't modify original value, returns new strings.

var city_name = 'Some text with spaces';

Replaces 1st space with _

city_name.replace(' ', '_'); // Returns: Some_text with spaces

Replaces all spaces with _ using regex. If you need to use regex, then i recommend testing it with https://regex101.com/

city_name.replace(/ /gi,'_');  // Returns: Some_text_with_spaces 

Replaces all spaces with _ without regex. Functional way.

city_name.split(' ').join('_');  // Returns: Some_text_with_spaces