I want to use str_replace
or its similar alternative to replace some text in JavaScript.
var text = \"this is some sample text that i want to re
function str_replace($old, $new, $text)
{
return ($text+"").split($old).join($new);
}
You do not need additional libraries.
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
that function replaces only one occurrence.. if you need to replace multiple occurrences you should try this function: http://phpjs.org/functions/str_replace:527
Not necessarily. see the Hans Kesting answer:
city_name = city_name.replace(/ /gi,'_');
If you don't want to use regex then you can use this function which will replace all in a string
function ReplaceAll(mystring, search_word, replace_with)
{
while (mystring.includes(search_word))
{
mystring = mystring.replace(search_word, replace_with);
}
return mystring;
}
var mystring = ReplaceAll("Test Test", "Test", "Hello");