i confused with this code
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "Microsoft" with "W3Schools" in the paragraph
below:</p>
<p id="demo">Microsoft Visit Microsoft! Microsoft visit visit microsoft Visit Visit
Visit Visit</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML.replace(/ Visit |Microsoft/gi, ' test ');
}
</script>
</body>
</html>
when click on button some words didn’t change,if click again will change
after first click
test test test ! test test visit test test Visit test Visit
after second click
test test test ! test test test test test test test test
why some words didn’t change in first time?
sincerely
This happens because in your
#democontents two not replacedVisitwords do not have space after it (the first has new line, the second has line end).In order to fix it, instead you may use
\bas word boundary:/\bVisit\b|Microsoft/gi.DEMO: http://jsfiddle.net/dyz5w/