How to use JavaScript to replace a portion of string with another value?

JavascriptWeb DevelopmentFront End Technology

In this article, we are going to explore replacing a portion of a string with another value using JavaScript. We can replace string parts in multiple ways. Below are some common methods −

  • replace() method

  • split() method

  • join() method

Let’s discuss the above methods in detail.

The replace() Method

This is an inbuilt method provided by JavaScript that allows the user to replace a part of a string with some another string or a regular expression. However, the original string will remain the same as earlier.

Syntax

string.replace(searchvalue, newvalue)

Parameters

  • searchvalue - It is used for searching a string in the whole string.

  • newvalue - It will replace the searched string.

The function will return a new string as an output to this method.

Example 1

In the below example, we will replace “Hi” with “Welcome To” using the JavaScript replace() method.

# index.html

<html>
<head>
   <title>Replacing String</title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <script>
      let string = "Hi Tutorials Point";
      /* It will search for Hi and then replace it with the another string */
      let replaced_string = string.replace("Hi", "Welcome To");
      document.write('<h4>The original string is:</h4>' +string);
      document.write('<h4>The replaced string is:</h4>' +replaced_string);
   </script>
</body>
</html>

Output

The split() Method

We can also use the split() method to split the string into an array of substrings. Once the string is converted into an array, we can compare each string with the string to be searched. When the string is found, we will replace it with the new string. The string split() method takes a separator with which we will split the string.

string.split(separator,limit)

The join() Method

The join() method is used for joining the array elements and returns it as a string. This method has only one optional parameter.

array.join(separator)

Example 2

# index.html

<html>
<head>
   <title>Replacing String</title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <script>
      let string = "Start Learning the latest technologies courses now.";
      let replaced_string = string.split("technologies").join("java");
      document.write("<h4>The replaced string is: </h4> " + replaced_string);
      document.write("<h4>The original string is: </h4>" + string);
   </script>
</body>
</html>

Output

raja
Updated on 26-Apr-2022 13:24:35

Advertisements