In my previous article on ES6 array methods, I introduced the new methods available in ECMAScript 6 that work with the Array type. In this tutorial, you’ll learn about new ES6 methods that work with strings: String.prototype.*
We’ll develop several examples, and mention the polyfills available for them. Remember that if you want to polyfill them all using a single library, you can employ es6-shim by Paul Miller.
One of the most-used functions in every modern programming language is the one to verify if a string starts with a given substring. Before ES6, JavaScript had no such function, meaning you had to write it yourself. The following code shows how developers usually polyfilled it:
<span>if (typeof String.prototype.startsWith !== 'function') { </span> <span>String.prototype.startsWith = function (str){ </span> <span>return this.indexOf(str) === 0; </span> <span>}; </span><span>} </span>
Or, alternatively:
<span>if (typeof String.prototype.startsWith !== 'function') { </span> <span>String.prototype.startsWith = function (str){ </span> <span>return this.substring(0, str.length) === str; </span> <span>}; </span><span>} </span>
These snippets are still valid, but they don’t reproduce exactly what the newly available String.prototype.startsWith() method does. The new method has the following syntax:
<span>String.prototype.startsWith(searchString[, position]); </span>
You can see that, in addition to a substring, it accepts a second argument. The searchString parameter specifies the substring you want to verify is the start of the string. position indicates the position at which to start the search. The default value of position is 0. The methods returns true if the string starts with the provided substring, and false otherwise. Remember that the method is case sensitive, so “Hello” is different from “hello”.
An example use of this method is shown below:
<span>if (typeof String.prototype.startsWith !== 'function') { </span> <span>String.prototype.startsWith = function (str){ </span> <span>return this.indexOf(str) === 0; </span> <span>}; </span><span>} </span>
A live demo of the previous code is shown below and also available at JSBin.
The method is supported in Node and all modern browsers, with the exception of Internet Explorer. If you need to support older browsers, a polyfill for this method can be found in the method’s page on MDN. Another polyfill has also been developed by Mathias Bynens.
In addition to String.prototype.startsWith(), ECMAScript 6 introduces the String.prototype.endsWith() method. It verifies that a string terminates with a given substring. The syntax of this method, shown below, is very similar to String.prototype.startsWith():
<span>if (typeof String.prototype.startsWith !== 'function') { </span> <span>String.prototype.startsWith = function (str){ </span> <span>return this.substring(0, str.length) === str; </span> <span>}; </span><span>} </span>
As you can see, this method accepts the same parameters as String.prototype.startsWith(), and also returns the same type of values.
A difference is that the position parameter lets you search within the string as if the string were only this long. In other words, if we have the string house and we call the method with 'house'.endsWith('us', 4), we obtain true, because it’s like we actually had the string hous (note the missing “e”).
An example use of this method is shown below:
<span>String.prototype.startsWith(searchString[, position]); </span>
A live demo of the previous snippet is shown below and is also available at JSBin.
The method is supported in Node and all modern browsers, with the exception of Internet Explorer. If you need to support older browsers, a polyfill for this method can be found in the method’s page on MDN. Another polyfill has been developed by Mathias Bynens.
While we’re talking about verifying if one string is contained in another, let me introduce you to the String.prototype.includes() method. It returns true if a string is contained in another, no matter where, and false otherwise.
Its syntax is shown below:
<span>const str = 'hello!'; </span><span>let result = str.startsWith('he'); </span> <span>// prints "true" </span><span>console.log(result); </span> <span>// verify starting from the third character </span>result <span>= str.startsWith('ll', 2); </span> <span>// prints "true" </span><span>console.log(result); </span>
The meaning of the parameters is the same as for String.prototype.startsWith(), so I won’t repeat them. An example use of this method is shown below:
<span>String.prototype.endsWith(searchString[, position]); </span>
You can find a live demo below and also as at JSBin.
String.prototype.includes() is supported in Node and all modern browsers, with the exception of Internet Explorer. If you need to support older browsers, as with the other methods discussed in this tutorial, you can find a polyfill provided by Mathias Bynens (this guy knows how to do his job!) and another on the Mozilla Developer Network.
Note: until version 48, Firefox uses the non-standard name contains.
Let’s now move on to another type of method. String.prototype.repeat() is a method that returns a new string containing the same string it was called upon but repeated a specified number of times. The syntax of this method is the following:
<span>if (typeof String.prototype.startsWith !== 'function') { </span> <span>String.prototype.startsWith = function (str){ </span> <span>return this.indexOf(str) === 0; </span> <span>}; </span><span>} </span>
The times parameter indicates the number of times the string must be repeated. If you pass zero you’ll obtain an empty string, while if you pass a negative number or infinity you’ll obtain a RangeError.
An example use of this method is shown below:
<span>if (typeof String.prototype.startsWith !== 'function') { </span> <span>String.prototype.startsWith = function (str){ </span> <span>return this.substring(0, str.length) === str; </span> <span>}; </span><span>} </span>
A live demo of the previous code is shown below and is also available at JSBin.
The method is supported in Node and all modern browsers, with the exception of Internet Explorer. If you need to support older browsers, two polyfills are available for this method: the one developed by Mathias Bynens and another on the Mozilla Developer Network.
The last method I want to cover in this tutorial is String.raw(). It’s defined as a tag function of template strings
. It’s interesting, because it’s kind of a replacement for templating libraries, although I’m not 100% sure it can scale enough to actually replace those libraries. However, the idea is basically the same as we’ll see shortly. What it does is to compile a string and replace every placeholder with a provided value.
Its syntax is the following (note the backticks):
<span>String.prototype.startsWith(searchString[, position]); </span>
The templateString parameter represents the string containing the template to process.
To better understand this concept, let’s see a concrete example:
<span>const str = 'hello!'; </span><span>let result = str.startsWith('he'); </span> <span>// prints "true" </span><span>console.log(result); </span> <span>// verify starting from the third character </span>result <span>= str.startsWith('ll', 2); </span> <span>// prints "true" </span><span>console.log(result); </span>
A live demo of the previous code is shown below and is also available at JSBin.
The method is supported in Node and all modern browsers, with the exception of Opera and Internet Explorer. If you need to support older browsers, you can employ a polyfill, such as this one available on npm.
In this tutorial, you’ve learned about several new methods introduced in ECMAScript 6 that work with strings. Other methods that we haven’t covered are String.fromCodePoint(), String.prototype.codePointAt(), and String.prototype.normalize(). I hope you enjoyed the article and that you’ll continue to follow our channel to learn more about ECMAScript 6.
ES6, also known as ECMAScript 2015, introduced several new string methods to make string manipulation easier and more efficient. These include methods like startsWith(), endsWith(), includes(), repeat(), and template literals. The startsWith() method checks if a string starts with a specified string, while endsWith() checks if a string ends with a specified string. The includes() method checks if a string contains a specified string. The repeat() method repeats a string a specified number of times. Template literals allow you to embed expressions within string literals, using ${} syntax.
The startsWith() method in ES6 is used to determine whether a string begins with the characters of a specified string. It returns true if the string starts with the specified string and false otherwise. The syntax is str.startsWith(searchString[, position]). The searchString is the characters to be searched for at the start of str. The position, which is optional, is the position in the string where the search should start. If omitted, the search starts at the beginning of the string.
The endsWith() method in ES6 is used to determine whether a string ends with the characters of a specified string. It returns true if the string ends with the specified string and false otherwise. The syntax is str.endsWith(searchString[, length]). The searchString is the characters to be searched for at the end of str. The length, which is optional, is the length of the string to be searched. If omitted, the length of the string is used.
The includes() method in ES6 is used to determine whether one string may be found within another string. It returns true if the string contains the specified string and false otherwise. The syntax is str.includes(searchString[, position]). The searchString is the string to search for. The position, which is optional, is the position within the string at which to begin searching. If omitted, the search starts at the beginning of the string.
The repeat() method in ES6 constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. The syntax is str.repeat(count), where count is the number of times to repeat the string. The count must be between 0 and less than infinity and not be a negative number.
Template literals in ES6 are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They are enclosed by the backtick ( ) character instead of double or single quotes. Template literals can contain placeholders, indicated by the dollar sign and curly braces (${expression}). The expressions in the placeholders and the text between them get passed to a function.
Both includes() and indexOf() methods are used to check if a string contains a specified string. However, there is a key difference between them. The includes() method returns a boolean value – true if the string contains the specified string, and false otherwise. On the other hand, the indexOf() method returns the index of the first occurrence of the specified string, or -1 if the string is not found.
Most modern browsers support ES6 string methods. However, for older browsers that do not support ES6, you may need to use a transpiler like Babel to convert ES6 code into ES5, which is more widely supported.
Some ES6 string methods can be used with arrays. For example, the includes() method can be used to determine whether an array contains a certain element. However, not all string methods are applicable to arrays. It’s important to understand the specific use and limitations of each method.
Tagged template literals in ES6 are more advanced form of template literals. With tagged templates, you can parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions. The tag function can then perform operations on these arguments and return manipulated string.
The above is the detailed content of Preparing for ECMAScript 6: New String Methods — String.prototype.*. For more information, please follow other related articles on the PHP Chinese website!