Replace multiple strings with multiple other strings - Javascript String Operation

Javascript examples for String Operation:String Replace

Description

Replace multiple strings with multiple other strings

Demo Code

ResultView the demo in separate window

<html>
   <head></head>
   <body> 
      <p id="demo">Mr Blue has a blue house and a blue car.</p> 
      <button onclick="myFunction()">Try it</button> 
      <script>
function myFunction() {/*from w  w  w  .j a va  2 s. com*/
    var str = document.getElementById("demo").innerHTML;
    var res = str.replace(/\n| |car/gi, function myFunction(x){
          if(x=='\n'){
             return x='<br>';
          }
          if(x==' '){
              return x='&nbsp';
          }
          if(x=='car'){
             return x='BMW'
          }else{
             return x;
          }
});
    document.getElementById("demo").innerHTML = res;
}

      </script>  
   </body>
</html>

Related Tutorials