How to replace character inside a string in JavaScript

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the JavaScript replace() method

You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global (g) modifier. The following example will show you how to replace all underscore (_) character in a string with hyphen (-).

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="UTF-8">
  • <title>Example of String Replace in JavaScript</title>
  • <script src="">
  • </script>
  • <script type="text/javascript">
  •     function strReplace(){
  •         var myStr = 'quick_brown_fox';
  •         var newStr = myStr.replace(/_/g, "-");
  •         // Insert modified string in paragraph
  •         $("p").html(newStr);
  •     }
  • </script>
  • </head>
  • <body>
  •     <p>quick_brown_fox</p>
  •     <button type="button" onclick="strReplace();">Replace</button>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:


Your Feedback:


We would love to hear from you! Please say something.