32

In PHP, you do this to replace more then one value at a time.

<?php
$string = "i am the foobar";

$newstring = str_replace(array('i', 'the'), array('you', 'a'), $string);

echo $newstring;
?>

How do you do this in javascript?

Marwelln
  • 28,492
  • 21
  • 93
  • 117
  • 4
    There are better answers in another question on Stackoverflow. In my opinion the best answers are [here](http://stackoverflow.com/questions/15604140/replace-multiple-strings-with-multiple-other-strings) – CodeChops Mar 29 '16 at 11:07

2 Answers2

80

Use javascript's .replace() method, stringing multiple replace's together. ie:

var somestring = "foo is an awesome foo bar foo foo"; //somestring lowercase
var replaced = somestring.replace(/foo/g, "bar").replace(/is/g, "or");
// replaced now contains: "bar or an awesome bar bar bar bar"
Community
  • 1
  • 1
Alex
  • 64,178
  • 48
  • 151
  • 180
  • 1
    Excellent just what I was looking for...I was dealing with dynamic strings so mine ended up looking something like var exp = new RegExp(foo, 'g'); somestring.replace(exp, 'bar'); – afreeland Dec 09 '14 at 14:13
  • Awesome very good solution. – Faris Rayhan Jul 15 '16 at 15:44
  • I want to replace several strings with one string. Like a->'', b->'',etc. Is there a better way than concatenate replace(s)? – Timo Jan 17 '21 at 10:36
16

You could do:

http://jsfiddle.net/ugKRr/

var string = "jak har en mamma";

string = string.replace(/(jak)|(mamma)/g,function(str,p1,p2) {
        if(p1) return 'du';
        if(p2) return 'pappa';
    });

or:

http://jsfiddle.net/ugKRr/2/

var string = "jak har en mamma";

string = string.replace(/jak/g,'du').replace(/mamma/g,'pappa');
user113716
  • 318,772
  • 63
  • 451
  • 440