Open In App

How to replace a portion of strings with another value in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

We can replace a portion of a string in multiple ways. Below the popular ones are mentioned and described with the example.

  1. JavaScript replace() Method
  2. Javascript split() Method
  3. Javascript join() Method

JavaScript replace() Method: We can replace a portion of String by using replace() method. JavaScript has an inbuilt method called replace which allows you to replace a part of a string with another string or regular expression. However, the original string will remain the same.

Syntax:

string.replace(searchvalue, newvalue)

The first parameter is used for searching a string in the whole string and the new string will replace the searched string. This function returns a new string but the original string remains the same.

Example 1:

HTML




<script>
    let string = "GeeksForGeeks";
    /* It first search 'For' in original string then it will 
    replace the searched string('For') with new string ('and') */
  
    let replaced_string = string.replace("For", "and");
    console.log("The original string is " + string);
    console.log("The replaced string is " + replaced_string);
</script>


Output:

The original string is GeeksForGeeks
The replaced string is GeeksandGeeks

We can also use two inbuilt javascript function split and join functions together to do this task.

Javascript split() Method: The split function is a javascript inbuilt function that is used to split a string into an array of substrings. This function takes two optional parameters as arguments such as separator and limit. The separator is a string or any character which belongs to the original string. Splitting is done with this character (or regular expression). If this character is omitted, the original string will be returned as an array. A limit is a type of integer that tells about the number of splits that are made.

string.split(separator,limit)

JavaScript join() Method: The join function is a javascript inbuilt function that is used to join the array of elements and return it as a string. This method has only one optional parameter.

array.join(separator)

Example 2: Here we use method chaining to use both the methods together at a time.

HTML




<script>
    let string = "GeeksForGeeks";
    /* split method split the string into an 
       array(['Geeks','Geeks']) and the join method will 
       join the string with another string ('and') */
  
    let replaced_string = string.split("For").join("and");
    console.log("The replaced string is " + replaced_string);
    console.log("The original string is " + string);
</script>


Output:

The replaced string is GeeksandGeeks
The original string is GeeksForGeeks


Last Updated : 30 Nov, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads