endsWith() strings and startsWith() strings xoxo
Strings only, sorry not sorry RegEx.
Table of contents
endsWith
endsWith()
will check if a string ends with the characters of the string you feed it, returning true
or false
.
It takes two parameters: the first one consists of the characters you want to find at the end of the string - and this can't be a regular expression.
The second parameter is optional, and it's the end position where you expect your first parameter to end. If you don't provide one it'll just default to the .length
of the string, to try and find the first parameter at the end.
To help visualize it better:
let string = "I don't see any train. All I see is a giant sneaker."
string.length
//output: 52
string.endsWith('sneaker')
//output: false
string.endsWith('.')
//output: true
string.endsWith(' sneaker.')
//output: true
string.endsWith('sneaker', string.length - 1)
//output: true
string.endsWith('sneaker', 51)
//output: true
string.endsWith('train', '21')
//output: true
startsWith
startsWith()
goes the other way around! It'll check if a string starts with a string parameter you feed it, start checking from 0 by default, and return true
or false
.
The second, optional parameter is a number representing the position in the string where you expect the first parameter to start!
let string = "I don't see any train. All I see is a giant sneaker."
string.startsWith("I don't")
//output: true
string.startsWith("don't", 2)
//output: true
string.startsWith("don't", "2")
//output: true
string.startsWith('.')
//output: false
string.startsWith('.', 21)
//output: true
Some practice exercises
These 8-kyu Kata are quick and fun:
As usual, JsKatas has awesome practice for startsWith and endsWith