endsWith() and startsWith(). Strings only, sorry not sorry RegEx.
The JavaScript String Methods series
- Part 0 - toUpperCase() and toLowerCase()
- Part 1 - split() and join()
- Part 2 - slice(), substring(), substr()
- Part 3 - charAt(), charCodeAt(), fromCharCode(), at()
- Part 4 - concat() and repeat()
- Part 5 - search() and includes()
- Part 6 - indexOf() and lastIndexOf()
- You are herePart 7 - endsWith() and startsWith()
- Part 8 - match() and matchAll()
- Part 9 - replace() and replaceAll()
- Part 10 - trim(), trimEnd() and trimStart()
- Part 11 - padStart() and padEnd()
In this post, skip to:
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