Tutorial :multiple replaces with javascript [duplicate]



Question:

This question already has an answer here:

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?


Solution:1

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"  


Solution:2

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »