- replace(): This method helps to remove a particular substring from a given string.
- substr(): This method helps extract the substring from a given string.
Method 1: Using the replace() function
It is required, This is a required argument for the given function. This defines the element that needs to be searched for.
Another required argument for the given function. This is the element with which the searchValue is to be replaced.
It returns a string.
let ourWord = "This is Old String"; let ourNewWord = ourWord.replace("Old", ""); console.log(ourNewWord)
This is String
In this example, we want to trim an “Old” substring with some “” empty substring by using the replace() function and assigning the new string to a new string variable. And then, we display the new string using the console.log() method.
Method 2: Using the substr() function
The following two special cases are associated with the argument:
- First, if the entered start value is greater than the length of the string, then the given function will return “”, which is an empty string. Second, on the hand, if the start is a negative number, the counting starts from the end of the string, i.e., reverse.
This parameter defines the number of extracted parts. If this parameter is not passed, it extracts all the parts of the string starting from the start position defined by the user.
It returns a string containing the extracted part. The function can also return an empty string.
let ourWord = "This is Old String."; let ourNewWord = ourWord.substr(8, 3); console.log(ourNewWord)
In this example, we use the substr() function, which extracts the substring starting from index 8 up to 3 lengths. Then, as an output, we get “Old” displayed on the console using the console.log() function.
Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.