DEV Community

Avnish Jayaswal
Avnish Jayaswal

Posted on • Originally published at askavy.com

javascript replace string

How to use the string method replace() with syntax and examples , How to replace all occurrence from string, How to replace srting using regular expression (regex)

javascript replace string() function used to replace occurrences of a specified string or regular expression with a replacement string.


   var string = "Blue need to replace";
   var result = string.replace(/Blue/g, "red");   //  red need to replace

 console.log(result);

Enter fullscreen mode Exit fullscreen mode

javascript regex replace

  var string = "Blue   need   to          replace";
  var result = string.replace(/\s{2,}/g, ' ');   // Blue need to replace

console.log(result);
Enter fullscreen mode Exit fullscreen mode

JavaScript replace special chars with empty strings Regex

 var string = "This is a <<<<!!!!st st>ring??? What ^^^";
 var result = string.replace(/[^a-zA-Z 0-9]+/g,'');   //  This is a st string What 

 console.log(result);
Enter fullscreen mode Exit fullscreen mode

Replace multiple characters in one replace (regex OR operator |)

 var string = "#Replace_string-example:";
 var result = string.replace(/#|_|-/g,' ');  // Replace string example: 

        console.log(result);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)