Using a function to return the replacement text: - Javascript String

Javascript examples for String:replace

Description

Using a function to return the replacement text:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<p id="demo">blue red pink.</p>

<button onclick="myFunction()">Test</button>

<script>
function myFunction() {/*from ww w  . j  ava2s.com*/
    var str = document.getElementById("demo").innerHTML;
    var res = str.replace(/blue|red|pink/gi, function myFunction(x){return x.toUpperCase();});
    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>

Related Tutorials