views:

63

answers:

3

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

<?php
$string = "jak har en mamma";

$newstring = str_replace(array('jak', 'mamma'), array('du', 'pappa'), $string);

echo $newstring;
?>

How do you do this in javascript?

+4  A: 

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

var someString = "foo is an awesome foo bar foo foo";
var replaced = somestring.replace(/foo/g, "bar").replace(/is/g, "or");
// replaced now contains: "bar or an awesome bar bar bar bar"
Alex
I think you missed foo bar. :) =~ s/array(foor, bar)/array(the, point)/g EDIT: The one with chaining I like.
ghaxx
Yes, at first I misunderstood the question, see my edited answer.
Alex
+3  A: 

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');
patrick dw
A: 

Still didnt work to replace spaces.

I did this and it worked:

var $val = $(this).val().replace(",", ".").split(' ').join('');

Thanks anyway!

Marwelln
How does that line of code have anything to do with the code you used in the question? All of the answers provided would have no problem replacing spaces. You are clearly doing something wrong. `string.replace(/ /g, '');` works, is more concise, and probably performs better. Also `.replace(",", ".")` will only replace the first `","`, is that what you want?
MooGoo