String replace() Method - Javascript String

Javascript examples for String:replace

Description

The replace() method replaces string by a string or a regular expression.

To replace all occurrences, use the global (g) modifier.

This method does not change the original string.

Syntax

string.replace(searchValue, newValue);

Parameter Values

Parameter Description
searchvalue Required. The value, or regular expression, that will be replaced by the new value
newvalueRequired. The value to replace the search value with

Return Value:

A new String, where the specified value(s) has been replaced by the new value

convert "blue", "red" and "yellow" to upper-case

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<p id="demo">Blue blue hour hourse red blue car.</p>

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

<script>
function myFunction() {/*from w w w. ja v a 2 s.  c o  m*/
    var str = document.getElementById("demo").innerHTML;
    var res = str.replace(/blue|red|yellow/gi, function myFunction(x){return x.toUpperCase();});
    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>

Related Tutorials