Skip to content

JavaScript replace function | Replace the specified value

  • by

Using JavaScript replace function, you can replace specified values. This method searches a string for a pattern or regular expression and If the pattern is found in the string then it replaces it with the new value.

string.replace(searchValue, newValue)

searchValue: the value, or regular expression, to search for.

newValue: The new value (to replace with).

Example JavaScript replace function

Simple example code.

<!DOCTYPE html>
<html>

<body>

  <script type="text/javascript">
    let text = "Hello Google!";
    let result = text.replace("Google", "EyeHunts");

    console.log(result)
  </script>

</body>
</html>

Output:

JavaScript replace function

Another example

<script type="text/javascript">
    let str = 'JS will, JS will rock you!';
    let newStr = str.replace('JS','JavaScript');

    console.log(newStr);
  </script>

Output: JavaScript will, JS will rock you!

Using regular expressions with replace function

The following example uses the global flag (g) to replace all occurrences of the JS in the str by the JavaScript:

<script type="text/javascript">
    let str = 'JS will, JS will rock you!';

    let newStr = str.replace(/JS/g , 'JavaScript');

    console.log(newStr);
  </script>

Output: JavaScript will, JavaScript will rock you!

Do comment if you have any doubts or suggestions on this Python this JS replace function.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *