This study will guide you through the methods for deleting a word from a string.
- substr() method
- replace() method
Let’s check out each of the mentioned methods individually.
Method 1: Remove a Word from a String Using substr() Method
The “substring()” method assists in removing a word from a string. It extracts the needed part of the string by passing the start and the end index of the substring. As a result, a substring between the start and the last index will be returned.
Follow the below-given syntax for using the substring() method:
In this example, first, we will create a variable that stores the following string:
Next, we will call the substr() method by passing the starting index as “0” and the ending index as “10”. It will extract the string from 0 to 10 indexes as a substring:
The above method just gets the specific part of the string. However, in case of deleting a particular word from a string, follow the next section!
Method 2: Remove a Word from a String Using replace() Method
You can use the “replace()” method for removing a word from a string. It is the most frequently simplest method. It accepts two parameters and gives a string with a specific replacement. You can also utilize this method to remove a single occurrence of any specific word in a string.
Follow the below-given syntax for using the replace() method:
Here, the “searchValue” is the value in a string that will be replaced, and the “replaceValue” is used as a replacement.
Let’s move to the example to learn more about the given method.
Example 1: Removing the First Occurrence of a Word from a String
First, we will create a variable named “str” that stores a string:
Now, we will remove the word “the” from the string by invoking the replace() method:
As you can see, the specified word is removed from the string:
Now, if you want to remove a word that occurs multiple times in the same string, what would you do? For this purpose, follow the next example.
Example 2: Removing All Occurrences of a Word from a String
In this example, we will remove the word with multiple occurrences in the string using replace() method with regex; as the regex checks the full string and replaces all the occurrences with the specified replacement value.
Here, we will create a variable that holds a string of words that appear more than once:
Now, we will replace all the “write” word with the empty string:
Here, the output shows that all the occurrences of the word “write” is successfully removed from the string:
We offered the methods related to removing words from the string.