Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you replace words in JavaScript?

To replace text in a JavaScript string the replace() function is used. The replace() function takes two arguments, the substring to be replaced and the new string that will take its place. Regex(p) can also be used to replace text in a string.

How do you overwrite a string in JavaScript?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

How do you replace all occurrences of a character in a string in JavaScript?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.


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" (replaced only 1st match)

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

You should write something like that :

var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);

The code that others are giving you only replace one occurrence, while using regular expressions replaces them all (like @sorgit said). To replace all the "want" with "not want", us this code:

var text = "this is some sample text that i want to replace";
var new_text = text.replace(/want/g, "dont want");
document.write(new_text);

The variable "new_text" will result in being "this is some sample text that i dont want to replace".

To get a quick guide to regular expressions, go here:
http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
To learn more about str.replace(), go here:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace
Good luck!