Source: "ES 6 Standard Getting Started" (2nd edition) - Ruan Yifeng the ---- Chapter 4 Expansion of the string
Traditionally, JavaScript only indexOf
method that can be used to determine whether a string is contained in another string. ES6 also provides three new methods.
- Includes () : returns a Boolean value that indicates whether to find a parameter string.
- startsWith () : returns a Boolean value indicating whether the parameter string at the head of the original string.
- endsWith () : returns a Boolean value indicating whether the parameter string at the end of the original string.
let s = 'Hello world!';
s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true
These three methods are supported by the second argument indicates the position to start the search.
let s = 'Hello world!';
s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false
The above codes indicate that the second parameter n
, the endsWith
behavior of the other two methods are different. It is for the previous n
characters, while the other two methods for from the first n
position until the end of the string.