Example 1:
Following example shows how to use the global and ignore case flags which permits replace to replace each occurrence of 'apples' in the string with 'oranges'.
Example 2:
Following example shows how to switch words in a string:
Following example shows how to use the global and ignore case flags which permits replace to replace each occurrence of 'apples' in the string with 'oranges'.
Code:
<html>
<head>
<title>JavaScript String replace() Method</title>
</head>
<body>
<script type="text/javascript">
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges");
document.write(newstr );
</script>
</body>
</html>
Example 2:
Following example shows how to switch words in a string:
Code:
<html>
<head>
<title>JavaScript String replace() Method</title>
</head>
<body>
<script type="text/javascript">
var re = /(\w+)\s(\w+)/;
var str = "zara ali";
var newstr = str.replace(re, "$2, $1");
document.write(newstr);
</script>
</body>
</html>