How to use replace() method In Javascript

The replace() method is used to replace the specified string with another string. It takes two parameters, the first is the string to be replaced and the second is the string that is replaced from the first string. The second string can be given an empty string so that the text to be replaced is removed. This method however only removes the first occurrence of the string. 

Syntax:

string.replace('textToReplace', '');

Example: This example replaces the first occurrence of the string. 

Javascript
// Function to remove text
function removeText() {
    // Input string
    let originalText = 'w3wiki';
    // Replace method to remove given text
    let newText = originalText.replace('Geeks', '');
    
    // Display output
    console.log(newText);
}

// Function call
removeText();

Output
ForGeeks

How to remove text from a string in JavaScript ?

We will have a string and we need to remove the given text from that string using JavaScript. We need to print the new string in the console.

These are the following methods to Remove Text from a String:

Table of Content

  • Method 1: Using replace() method
  • Method 2: Using replace() method with Regex
  • Method 3: Using substr() method
  • Method 4: Using replaceAll() method
  • Method 5: Using split() and join() method

Similar Reads

Method 1: Using replace() method

The replace() method is used to replace the specified string with another string. It takes two parameters, the first is the string to be replaced and the second is the string that is replaced from the first string. The second string can be given an empty string so that the text to be replaced is removed. This method however only removes the first occurrence of the string....

Method 2: Using replace() method with Regex

This method is used to remove all occurrences of the string specified, unlike the previous method. A regular expression is used instead of the string along with the global property. This will select every occurrence in the string and it can be removed by using an empty string in the second parameter....

Method 3: Using substr() method

The substr() method is used to extract parts of a string between the given parameters. This method takes two parameters, one is the starting index and the other is the length of the string to be selected from that index. By specifying the required length of the string needed, the other portion can be discarded. This can be used to remove prefixes or suffixes in a string....

Method 4: Using replaceAll() method

Example: In this article, we will use the JavaScript replaceAll() methods to remove all the occurrences of given text from the input string....

Method 5: Using split() and join() method

This method involves splitting the string into an array of substrings using the specified separator (the text to be removed), then joining the array back into a string without the removed text....