- By using the replace() method
- By using the slice() method
- By using the substring() method
Let’s explore each…
#1 – By using the replace() method
replace() method is used to replace a specified value or substring in a string with another value or substring. It creates a new string without altering the original one. To illustrate this, let’s consider an example where we want to remove the substring “World” from the string “Hello World”.
var str = "Hello World"; var newStr = str.replace("World", "");
How it works
replace() method scans the original string for the first match of the substring specified to be replaced (in this case “World”). When the method finds the substring, it replaces it with the new value specified (in this case, an empty string “”).
- The variable
stris initialized with the string “Hello World”.
replace()method is called on
strwith “World” as the value to be replaced and “” (empty string) as the replacement.
- Since “World” exists in
str, it is replaced with an empty string, effectively removing “World” from the string.
- The new string is then stored in the variable
- As a result,
newStrwill contain “Hello ” (with a trailing space) as it has removed “World”.
#2 – By using the slice() method
slice() method will be used to remove a substring from a string by identifying its start and end index. This technique will be demonstrated through an example.
var str = "Hello, World!"; var newStr = str.slice(0, 5) + str.slice(7);
How it works
slice()method takes two parameters: the start index and the end index. The start index is inclusive, whereas the end index is exclusive.
- In the provided code, two slices are made: one from index 0 to 5 (extracting “Hello”) and another from index 7 to the end of the string (extracting “World!”).
- Notice that the substring from index 5 to 7, i.e., “, ” is left out. This effectively removes that substring from the original string.
- The ‘+’ operator is then used to concatenate the two resulting strings, forming “HelloWorld!”
- The original string remains unchanged, and we have a new string without the undesired substring.
#3 – By using the substring() method
var originalString = "Hello World!"; var substringToRemove = " World"; var newString = originalString.replace(substringToRemove, ""); console.log(newString); // Outputs: "Hello!"
How it works
- Step 1: We define the original string: “Hello World!”.
- Step 2: We define the substring we want to remove: ” World”.
- Step 3: We use the replace() method on the original string. We pass the substring to remove as the first parameter and an empty string as the second parameter. This replaces the substring with nothing, effectively removing it.
- Step 4: The replace() method returns a new string with the specified substring removed. We store this new string in a variable.
- Step 5: We print the new string to the console. The output is: “Hello!”.