replace javascript code example
Example 1: javascript replace all
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
console.log(p.replaceAll('dog', 'monkey'));
const regex = /Dog/ig;
console.log(p.replaceAll(regex, 'ferret'));
Example 2: javascript replace string
var str = "JavaScript replace method test";
var res = str.replace("test", "success");
Example 3: replacing characters in string javascript
var myStr = 'this,is,a,test';
var newStr = myStr.replace(/,/g, '-');
console.log( newStr );
Example 4: javascript replace element
<html>
<head>
</head>
<body>
<div>
<a id="myAnchor" href="http://www.stackoverflow.com">StackOverflow</a>
</div>
<script type="text/JavaScript">
var myAnchor = document.getElementById("myAnchor");
var mySpan = document.createElement("span");
mySpan.innerHTML = "replaced anchor!";
myAnchor.parentNode.replaceChild(mySpan, myAnchor);
</script>
</body>
</html>
Example 5: javascript replace
var res = str.replace("find", "replace");
Example 6: js replace characters in a string
var str = "Original string!";
var str = str.replace("Original", "New");