Let us explore different ways to removing characters from a string.
Also read: How to Split a String in Node.js?
Getting Started with Removing Characters from a String
You can try multiple ways to remove characters from a string. Below listed are methods we can use on a string, to achieve the same:
Let’s get started by explaining all the above-listed ways and illustrating with examples.
Note: Some arguments mentioned below are enclosed in [ ] – square brackets. This means that they are optional.
The substr() method accepts two arguments; a starting position and the length of the string to be extracted.
This method takes out or extracts the characters of the string beginning from the specified position, and returns it and is of the specified length.
Let’s illustrate this through an example:
// "ood d"
Note that the count of the position starts at 0. Hence, if you include the first character from your string, you may do this:
// "Good "
Here’s a tip! To begin extraction from the end of the string, you can use a negative number.
This method will not modify your original string in any way.
It may seem like substring() is just a longer version of the substr() method and you’d be partially correct. The difference between both the methods is in the second argument. The second argument to
Well, the substring() method accepts an ending position argument. Moreover, the outputs that these two methods provide, also differ.
Let us check with the same string and arguments passed to the previous method.
// "ood "
The substring() method extracts characters residing in between the specified starting position and the specified ending position of the string and returns that new string. The last character is excluded.
Also, if the start argument is greater than the end argument, this method will swap the arguments meaning (5, 1) will become (1, 5).
If the start or end positions are below 0, they will be considered as 0. Similar to substr(), this method too doesn’t modify the original string.
This method, like the substring() method, accepts two positional arguments; a start and an end.
The method basically “slices” or extracts parts of the string between the specified start and end positions, and returns it.
Again, the count begins from 0. You may also use a negative number to begin slicing from the end of the string.
Let us learn this with an example:
// "day, Brend"
Notice, the last character here too is excluded. This method doesn’t change the original string.
The replace() method on a string helps to replace the characters or the entire string, with a character(s) or string(s).
Let us check with an example:
// "Good day, Ozuna!"
Removes space characters, whitespace, and indents at the farthest ends of the string, and not between it. This method doesn’t modify the original string.
Also, trim() doesn’t accept any parameters/arguments to it. Let us cite an example:
// "Good day, Ozuna!"