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. //The return value is a string data type, and it is the new string where the given values have been replaced.
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.
Trimming all occurrences of a specific substring
let ourWord = "This is Old String. To replace the word Old we need to use RegX and Old will be trimmed."; let ourNewWord = ourWord.replace(/Old/g, ""); console.log(ourNewWord);
This is String. To replace the word we need to use RegX and will be trimmed.
By using a regular expression, all the occurrences of the specified substring will be replaced by the other as shown in the above code, and we are replacing Old with New value.
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.
- If the start is, on the other hand, a negative number, then 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 is extracting the substring starting from index 8 up to 3 lengths. As an output, we get “Old” displayed on the console using the console.log() function.
That’s it for this tutorial.