/

HTML / CSS / JavaScript Tutorial

JavaScript String method: replace()

[this page | pdf | back links]

The replace() method (when applied to a JavaScript string) returns a string that repeats a specified string a specified number of times.

 

It has the following syntax with the following parameters:

 

string.replace(searchvalue)

 

Parameter

Required / Optional

Description

searchvalue

Required

Value or regular expression to be replaced

newvalue

Required

New value inserted instead

 

If searchvalue is a normal string then only the first occurrence is replaced, if it occurs more than once in the string being searched. If you want to replace all occurrences then you need to use a corresponding regular expression with a /g, i.e. global, modifier.

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>

<script>
var str1 = "ababab";
document.getElementById("Example").innerHTML =
  'var str1 = "' + str1 + '";<br>' +
  'var x1 = str1.replace("ab", "cd");<br>' +
  'var x2 = str1.replace(/ab/g, "cd");<br>' +
  'var x3 = str1.replace(/ab/g, <br>' +
  '&nbsp;&nbsp;function f(x){return x.toUpperCase();});<br>' +
  'var x = x1 + "&lt;br&gt;" + x2 + "&lt;br&gt;" + x3;';
document.getElementById("Result").innerHTML =
  str1.replace('ab','cd') +'<br>' + 
  str1.replace(/ab/g, 'cd')  +'<br>' + 
  str1.replace(/ab/g, function f(x){return x.toUpperCase();});
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodStringReplace() {
  var z = "abc"; return !!z.replace;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript String Variables


Desktop view | Switch to Mobile