Q:

How to replace character inside a string in JavaScript

0

How to replace character inside a string in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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>JavaScript Replace Character in a String</title>
<script>
    function strReplace(){
        var myStr = 'quick_brown_fox';
        var newStr = myStr.replace(/_/g, "-");
        
        // Insert modified string in paragraph
        document.getElementById("myText").innerHTML = newStr;
    }
</script>
</head>
<body>
    <p id="myText">quick_brown_fox</p>
    <button type="button" onclick="strReplace();">Replace</button>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to explode or split a string in JavaScript... >>
<< How to loop through an array in JavaScript...