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

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 replace";
var new_text = replace_in_javascript("want", "dont want", text);
document.write("new_text");

should give

this is some sample text that i dont want to replace

If you are going to regex, what are the performance implications in comparison to the built in replacement methods.

This question is related to javascript replace str-replace

The answer is


Use JS String.prototype.replace first argument should be Regex pattern or String and Second argument should be a String or function.

str.replace(regexp|substr, newSubStr|function);

Ex:

var str = 'this is some sample text that i want to replace'; var newstr = str.replace(/want/i, "dont't want"); document.write(newstr); // this is some sample text that i don't want to replace


You can use

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

And to change multiple values in one string at once, for example to change # to string v and _ to string w:

text.replace(/#|_/g,function(match) {return (match=="#")? v: w;});

In JavaScript, you call the replace method on the String object, e.g. "this is some sample text that i want to replace".replace("want", "dont want"), which will return the replaced string.

var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want"); // new_text now stores the replaced string, leaving the original untouched

If you don't want to use regex then you can use this function which will replace all in a string

Source Code:

function ReplaceAll(mystring, search_word, replace_with) 
{
    while (mystring.includes(search_word))
    {
        mystring = mystring.replace(search_word, replace_with);
    }

    return mystring;  
}

How to use:

var mystring = ReplaceAll("Test Test", "Test", "Hello"); 

Method to replace substring in a sentence using React:

 const replace_in_javascript = (oldSubStr, newSubStr, sentence) => {
    let newStr = "";
    let i = 0;
    sentence.split(" ").forEach(obj => {
      if (obj.toUpperCase() === oldSubStr.toUpperCase()) {
        newStr = i === 0 ? newSubStr : newStr + " " + newSubStr;
        i = i + 1;
      } else {
        newStr = i === 0 ? obj : newStr + " " + obj;
        i = i + 1;
      }
    });
    return newStr;
  };

RunMethodHere


var new_text = text.replace("want", "dont want");

In ECMAScript 2021, you can use replaceAll can be used.

const str = "string1 string1 string1"
const newStr = str.replaceAll("string1", "string2");

console.log(newStr)
//  "string2 string2 string2"

More simply:

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

Replaces all spaces with '_'!


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.


In Javascript, replace function available to replace sub-string from given string with new one. Use:

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

You can even use regular expression with this function. For example, if want to replace all occurrences of , with ..

var text = "123,123,123";
var new_text = text.replace(/,/g, ".");
console.log(new_text);

Here g modifier used to match globally all available matches.


function str_replace($old, $new, $text)
{
   return ($text+"").split($old).join($new); 
}

You do not need additional libraries.


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,'_');

You have the following options:

  1. Replace the first occurrence

_x000D_
_x000D_
var text = "this is some sample text that i want to replace and this i WANT to replace as well.";_x000D_
var new_text = text.replace('want', 'dont want');_x000D_
// new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well"_x000D_
console.log(new_text)
_x000D_
_x000D_
_x000D_

  1. Replace all occurrences - case sensitive

_x000D_
_x000D_
var text = "this is some sample text that i want to replace and this i WANT to replace as well.";_x000D_
var new_text = text.replace(/want/g, 'dont want');_x000D_
// new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well_x000D_
console.log(new_text)
_x000D_
_x000D_
_x000D_

  1. Replace all occurrences - case insensitive

_x000D_
_x000D_
var text = "this is some sample text that i want to replace and this i WANT to replace as well.";_x000D_
var new_text = text.replace(/want/gi, 'dont want');_x000D_
// new_text is "this is some sample text that i dont want to replace and this i dont want to replace as well_x000D_
console.log(new_text)
_x000D_
_x000D_
_x000D_

More info -> here


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

hm.. Did you check replace() ?

Your code will look like this

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

JavaScript has replace() method of String object for replacing substrings. This method can have two arguments. The first argument can be a string or a regular expression pattern (regExp object) and the second argument can be a string or a function. An example of replace() method having both string arguments is shown below.

var text = 'one, two, three, one, five, one';
var new_text = text.replace('one', 'ten');
console.log(new_text)  //ten, two, three, one, five, one

Note that if the first argument is the string, only the first occurrence of the substring is replaced as in the example above. To replace all occurrences of the substring you need to provide a regular expression with a g (global) flag. If you do not provide the global flag, only the first occurrence of the substring will be replaced even if you provide the regular expression as the first argument. So let's replace all occurrences of one in the above example.

var text = 'one, two, three, one, five, one';
var new_text = text.replace(/one/g, 'ten');
console.log(new_text)  //ten, two, three, ten, five, ten

Note that you do not wrap the regular expression pattern in quotes which will make it a string not a regExp object. To do a case insensitive replacement you need to provide additional flag i which makes the pattern case-insensitive. In that case the above regular expression will be /one/gi. Notice the i flag added here.

If the second argument has a function and if there is a match the function is passed with three arguments. The arguments the function gets are the match, position of the match and the original text. You need to return what that match should be replaced with. For example,

var text = 'one, two, three, one, five, one';
var new_text = text.replace(/one/g, function(match, pos, text){
return 'ten';
});
console.log(new_text) //ten, two, three, ten, five, ten

You can have more control over the replacement text using a function as the second argument.


There are already multiple answers using str.replace() (which is fair enough for this question) and regex but you can use combination of str.split() and join() together which is faster than str.replace() and regex.

Below is working example:

_x000D_
_x000D_
var text = "this is some sample text that i want to replace";_x000D_
_x000D_
console.log(text.split("want").join("dont want"));
_x000D_
_x000D_
_x000D_


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);

If you really want a equivalent to PHP's str_replace you can use Locutus. PHP's version of str_replace support more option then what the JavaScript String.prototype.replace supports. For example tags:

//PHP
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
//JS with Locutus
var $bodytag = str_replace(['{body}', 'black', '<body text='{body}'>')  

or array's

//PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
//JS with Locutus
var $vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"];
var $onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

Also this doesn't use regex instead it uses for loops. If you not want to use regex but want simple string replace you can use something like this ( based on Locutus )

_x000D_
_x000D_
function str_replace (search, replace, subject) {_x000D_
_x000D_
  var i = 0_x000D_
  var j = 0_x000D_
  var temp = ''_x000D_
  var repl = ''_x000D_
  var sl = 0_x000D_
  var fl = 0_x000D_
  var f = [].concat(search)_x000D_
  var r = [].concat(replace)_x000D_
  var s = subject_x000D_
  s = [].concat(s)_x000D_
_x000D_
  for (i = 0, sl = s.length; i < sl; i++) {_x000D_
    if (s[i] === '') {_x000D_
      continue_x000D_
    }_x000D_
    for (j = 0, fl = f.length; j < fl; j++) {_x000D_
      temp = s[i] + ''_x000D_
      repl = r[0]_x000D_
      s[i] = (temp).split(f[j]).join(repl)_x000D_
      if (typeof countObj !== 'undefined') {_x000D_
        countObj.value += ((temp.split(f[j])).length - 1)_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  return s[0]_x000D_
}_x000D_
var text = "this is some sample text that i want to replace";_x000D_
_x000D_
var new_text = str_replace ("want", "dont want", text)_x000D_
document.write(new_text)
_x000D_
_x000D_
_x000D_

for more info see the source code https://github.com/kvz/locutus/blob/master/src/php/strings/str_replace.js


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!


Added a method replace_in_javascript which will satisfy your requirement. Also found that you are writing a string "new_text" in document.write() which is supposed to refer to a variable new_text.

_x000D_
_x000D_
let replace_in_javascript= (replaceble, replaceTo, text) => {_x000D_
  return text.replace(replaceble, replaceTo)_x000D_
}_x000D_
_x000D_
var text = "this is some sample text that i want to replace";_x000D_
var new_text = replace_in_javascript("want", "dont want", text);_x000D_
document.write(new_text);
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to replace

How do I find and replace all occurrences (in all files) in Visual Studio Code? How to find and replace with regex in excel How to replace text in a column of a Pandas dataframe? How to replace negative numbers in Pandas Data Frame by zero Replacing few values in a pandas dataframe column with another value How to replace multiple patterns at once with sed? Using tr to replace newline with space replace special characters in a string python Replace None with NaN in pandas dataframe Batch script to find and replace a string in text file within a minute for files up to 12 MB

Examples related to str-replace

C# string replace str_replace with array PHP str_replace replace spaces with underscores Str_replace for multiple items How to Replace dot (.) in a string in Java How can I perform a str_replace in JavaScript, replacing text in JavaScript? How to replace all occurrences of a character in string?