144

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.

user3840170
  • 26,597
  • 4
  • 30
  • 62
Vish
  • 4,508
  • 10
  • 42
  • 74
  • 3
    Strange nobody noticed that PHP's `str_replace` also accepts two arrays of the same length, where each string in the first array is replaced with the string in the second array at the same index. Please see http://stackoverflow.com/a/5069776/296430 for the only correct function I have found so far that mimics this exact behavior in javascript. – Jules Colle Sep 02 '13 at 00:08
  • 2
    @JulesColle that answer fails often -- see why/when it fails and a better solution here: http://stackoverflow.com/a/37949642/445295 – Stephen M. Harris Jun 21 '16 at 16:24
  • 1
    If you want high compatibility -- including quirks -- with the php version... take a look at https://github.com/kvz/locutus/blob/master/src/php/strings/str_replace.js – Doug Coburn Jul 09 '18 at 17:23

25 Answers25

209

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.

Mild Fuzz
  • 29,463
  • 31
  • 100
  • 148
sdleihssirhc
  • 42,000
  • 6
  • 53
  • 67
  • 4
    Thanks a lot for the 'it only returns and does not change'! That was what I was tearing my hair about for a long time till I came across the your comment... – Aditya M P Nov 26 '11 at 04:25
  • 73
    string.replace('old','new') will only replace the first instance of 'old' in the string. using a regular expression with the 'g' flag like in realmag777's answer will replace all instances of the string. text = text.replace(/old/g, 'new') will replace all instances of 'old' – WNRosenberg May 31 '12 at 14:44
  • 1
    how about not case-sensitive? – Netorica Jun 04 '12 at 11:17
  • 7
    ^ text.replace(/old/gi, 'new') will replace all instances of 'old' for 'new' not case-sensitive (e.g. 'OLD' and 'oLd' will be replaced as well) – arnoudhgz Jan 16 '14 at 15:53
  • 2
    and some docs with that: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace – elad silver May 20 '15 at 15:27
89

More simply:

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

Replaces all spaces with '_'!

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
realmag777
  • 2,050
  • 1
  • 24
  • 22
  • 10
    this is a more accurate translation of what "str_replace" does (global). The chosen answer will only replace the first instance. – rICh May 15 '12 at 21:53
  • 1
    Don't forget to escape characters, especially if you're replacing hex escaped: \x27 for example would be `.replace(/\\x3B/g,';')` – dmayo Oct 14 '16 at 18:44
20

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
Lukas Liesis
  • 24,652
  • 10
  • 111
  • 109
17

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);
Timon. Z
  • 681
  • 3
  • 9
16

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!

Zoyt
  • 4,809
  • 6
  • 33
  • 45
15

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,'_');
Siamak Motlagh
  • 5,028
  • 7
  • 41
  • 65
Pavel
  • 542
  • 5
  • 11
13

Using regex for string replacement is significantly slower than using a string replace.
As demonstrated on JSPerf, you can have different levels of efficiency for creating a regex, but all of them are significantly slower than a simple string replace. The regex is slower because:

Fixed-string matches don't have backtracking, compilation steps, ranges, character classes, or a host of other features that slow down the regular expression engine. There are certainly ways to optimize regex matches, but I think it's unlikely to beat indexing into a string in the common case.

For a simple test run on the JS perf page, I've documented some of the results:

<script>
// Setup
  var startString = "xxxxxxxxxabcxxxxxxabcxx";
  var endStringRegEx = undefined;
  var endStringString = undefined;
  var endStringRegExNewStr = undefined;
  var endStringRegExNew = undefined;
  var endStringStoredRegEx = undefined;      
  var re = new RegExp("abc", "g");
</script>

<script>
// Tests
  endStringRegEx = startString.replace(/abc/g, "def") // Regex
  endStringString = startString.replace("abc", "def", "g") // String
  endStringRegExNewStr = startString.replace(new RegExp("abc", "g"), "def"); // New Regex String
  endStringRegExNew = startString.replace(new RegExp(/abc/g), "def"); // New Regexp
  endStringStoredRegEx = startString.replace(re, "def") // saved regex
</script>

The results for Chrome 68 are as follows:

String replace:    9,936,093 operations/sec
Saved regex:       5,725,506 operations/sec
Regex:             5,529,504 operations/sec
New Regex String:  3,571,180 operations/sec
New Regex:         3,224,919 operations/sec

From the sake of completeness of this answer (borrowing from the comments), it's worth mentioning that .replace only replaces the first instance of the matched character. Its only possible to replace all instances with //g. The performance trade off and code elegance could be argued to be worse if replacing multiple instances name.replace(' ', '_').replace(' ', '_').replace(' ', '_'); or worse while (name.includes(' ')) { name = name.replace(' ', '_') }

TheChetan
  • 4,440
  • 3
  • 32
  • 41
  • Thats interesting and makes sense that pure string replace is faster than regex. It's probably worth mentioning (like in some answers) that `.replace` only replaces the first instance of the matched character. Its only possible to replace all instances with `//g`. The performance trade off could be argued to be worse if replacing multiple instances `name.replace(' ', '_').replace(' ', '_').replace(' ', '_');` or worse `while (name.includes(' ')) { name = name.replace(' ', '_') }` – Lex Jul 09 '18 at 23:31
9
var new_text = text.replace("want", "dont want");
Town
  • 14,706
  • 3
  • 48
  • 72
9

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);
Timon. Z
  • 681
  • 3
  • 9
arbithero
  • 426
  • 3
  • 13
8

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.

Saral
  • 1,087
  • 1
  • 8
  • 18
7

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
4

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;});
aabiro
  • 3,842
  • 2
  • 23
  • 36
3

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:

var text = "this is some sample text that i want to replace";

console.log(text.split("want").join("dont want"));
Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
3

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 )

function str_replace (search, replace, subject) {

  var i = 0
  var j = 0
  var temp = ''
  var repl = ''
  var sl = 0
  var fl = 0
  var f = [].concat(search)
  var r = [].concat(replace)
  var s = subject
  s = [].concat(s)

  for (i = 0, sl = s.length; i < sl; i++) {
    if (s[i] === '') {
      continue
    }
    for (j = 0, fl = f.length; j < fl; j++) {
      temp = s[i] + ''
      repl = r[0]
      s[i] = (temp).split(f[j]).join(repl)
      if (typeof countObj !== 'undefined') {
        countObj.value += ((temp.split(f[j])).length - 1)
      }
    }
  }
  return s[0]
}
var text = "this is some sample text that i want to replace";

var new_text = str_replace ("want", "dont want", text)
document.write(new_text)

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

Victor Perez
  • 470
  • 3
  • 10
2

You have the following options:

  1. Replace the first occurrence

var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace('want', 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well"
console.log(new_text)
  1. Replace all occurrences - case sensitive

var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace(/want/g, 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well
console.log(new_text)
  1. Replace all occurrences - case insensitive

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

More info -> here

Svetoslav Petrov
  • 1,036
  • 1
  • 11
  • 33
2

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.

Lovepreet Singh
  • 4,792
  • 1
  • 18
  • 36
2

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

bh4r4th
  • 3,760
  • 1
  • 21
  • 25
2

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"); 
al000y
  • 139
  • 3
  • 4
2

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

Oli
  • 651
  • 8
  • 17
2

ES2021 / ES12

String.prototype.replaceAll()

is trying to bring the full replacement option even when the input pattern is a string.

const str = "Backbencher sits at the Back";
const newStr = str.replaceAll("Back", "Front");
console.log(newStr); // "Frontbencher sits at the Front"

1- String.prototype.replace()

We can do a full **replacement** only if we supply the pattern as a regular expression.
const str = "Backbencher sits at the Back";
const newStr = str.replace(/Back/g, "Front");
console.log(newStr); // "Frontbencher sits at the Front"

If the input pattern is a string, replace() method only replaces the first occurrence.

const str = "Backbencher sits at the Back";
const newStr = str.replace("Back", "Front");
console.log(newStr); // "Frontbencher sits at the Back"

2- You can use split and join

const str = "Backbencher sits at the Back";
const newStr = str.split("Back").join("Front");
console.log(newStr); // "Frontbencher sits at the Front"
Abolfazl Roshanzamir
  • 12,730
  • 5
  • 63
  • 79
0
function str_replace($old, $new, $text)
{
   return ($text+"").split($old).join($new); 
}

You do not need additional libraries.

18C
  • 2,014
  • 10
  • 16
0

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"
SuperNova
  • 25,512
  • 7
  • 93
  • 64
0

simplest form as below

if you need to replace only first occurrence

var newString = oldStr.replace('want', 'dont want');

if you want ot repalce all occurenace

var newString = oldStr.replace(want/g, 'dont want');
Ali
  • 1,080
  • 16
  • 22
0

The in-built function in JavaScript is the ".replace()" function. The syntax of the .replace() function is as follows:

" <string_name>.replace('text to edit', 'text to replace it with' ); "

Hence, in a string, the whole or part of the string can be replaced with some other value using this in-built function.

For example, let the string s be: "I practice development with the help of the Coding Ninjas website." And the code is as follows:

let news=s.replace("website", "Website");

Then, if we print the string news, it will be as follows: "I practice development with the help of the Coding Ninjas Website."

Also, you can use it multiple times to replace various texts of the string located in different positions. Like,

let news=s
.replace("development", "Development")
.replace("with", "With");
console.log(news);

These statements will result in the following output: "I practice Development With the help of the Coding Ninjas website."

Also, if there is more than one instance of the text you have written that you want to replace with some other text, only the first instance of the text will be replaced. For example,

let news = s.replace("the", "The");
console.log(news);

It will only replace the first 'the', resulting as follows: "I practice development with The help of the Coding Ninjas website." Hence, if you want to replace all the instances of a substring of the string, you would have to use the ".replaceAll()" method.

Now, if you want to replace multiple substrings with one text, you can use the following syntax of the commands: let news = s.replace(/practice|development/g, "study"); console.log(news); The output will be: "I study study with the help of the Coding Ninjas website."

Also, you can try the following syntax of the command to use the ".replace()" function with regular expressions. let news=s.replace(/the/g, "The"); console.log(news);

The output of these commands will be as the following: "I practice development with The help of The Coding Ninjas website." Here, the "/g" specifies that all the occurrences of the substring "the" should be replaced with "The" substring.

LW001
  • 2,452
  • 6
  • 27
  • 36
-1

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.

let replace_in_javascript= (replaceble, replaceTo, text) => {
  return text.replace(replaceble, replaceTo)
}

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);
karthik
  • 1,100
  • 9
  • 21