Checkout this video:
var str = “Hello, world!”;
And you want to remove the exclamation point at the end of the string, so that the new string would be “Hello, world”. In this article, we’ll show you three different ways that you can accomplish this.
The string.prototype.slice() method extracts a section of a string and returns a new string. The method takes two arguments, the first being the index at which to begin extraction, and the second being the index at which to end extraction (extraction will occur up to, but not including the index passed for the second argument). If no second argument is passed, slice() will extract to the end of the string.
The substring() method extracts the characters from a string, between two specified indices, and returns the new sub string.
This method extracts the characters in a string between “start” and “end”, not including “end” itself.
If “start” is greater than “end”, this method will swap the two arguments, meaning str.substring(1, 4) == str.substring(4, 1). If either “start” or “end” is less than 0, it is treated as if it were 0.
The String.prototype.substr() method returns a subset of a string between one index and another, or through the end of the string.
This method has two overloads:
Both overloads take an integer as a parameter. The first form calculates the result by using start as the starting index and counting up to the end of the string; it’s equivalent to calling substr(start, this.length-start). The second form uses both start and length parameters. It calculates the result by using start as the starting index and length as a count of characters.
If either parameter is negative, it’s treated as if it were 0 instead (i.e., substr(0) always returns an empty string). If start is greater than this string’s length, substr() returns an empty string. If length is zero or negative, substr() returns an empty string also whether start is 0 or not (i.e., substr(0,-1) always returns an empty string).
Using Regular Expressions