33

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?

1
  • 4
    There are better answers in another question on Stackoverflow. In my opinion the best answers are here Commented Mar 29, 2016 at 11:07

2 Answers 2

81

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"
Sign up to request clarification or add additional context in comments.

3 Comments

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');
Awesome very good solution.
I want to replace several strings with one string. Like a->'', b->'',etc. Is there a better way than concatenate replace(s)?
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');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.