We can use replace() method to replace any string or character with another in javascript. It searches for a defined string, character, or regular expression and replaces it. This method doesn’t change the original string but it returns the updated string as result.

Advertisement

Syntax:

string.replace(old_string, new_string)

Replace String in JavaScript with Examples

In this tutorial, we will discuss a few examples of replacing strings in Javascript.

Let’s try some examples:

  • Here is the first example to initialize a text in a variable, then replace it with another text.

    Run the above example and see the results. Thanks to playcode.io that help me to run javascript online.

    How to Replace String in JavaScript
    Replace string in javascript
  • What happens if a given string is found multiple times. In that case, the replace() function will replace the first occurrence of the given string.

    Execute the above code and see the results:

    Replace first matching string in javascript

    The result clearly shows that the first occurrence is replaced with a new string, but the second occurrence is not replaced. So, how can I replace all the occurrences of a given string? Let’s check the next example:

  • We can also define the regular expression and the function will replace all occurrences matching that regular expression.

    See the below example, where we defined a regular expression to replace string globally.

    Run the above example and see the results.

    Replace string with regular expression in JavaScript
  • Basically, the regular expression is used to match patterns. To replace all occurrences of any string, we can use replaceAll() function.

    The below example uses the replaceAll() function in javascript.

    Run the above code and see the results.

    Replace all matching strings in JavaScript

Wrap Up

In this tutorial, we have discussed a few examples to replace a string in javascript.

Share.
Leave A Reply


Exit mobile version