I have to admit, I was a few years behind the curve when it came to all the new functionality in ES6 aka ECMAScript 2015 aka ECMAScript 6. When I finally did start to learn it and get up to speed, I was primarily interested in the arrow functions, destructuring, array methods, etc. I didn't pay much attention to the new functionality added to the String
object.
NOTE: If you need to get up to speed yourself, I can highly recommend the excellent ES6 for Everyone course by Wes Bos. Wes is a fun and engaging trainer with a slew of high quality courses. (See a review of another course here). Here are some other training suggestions for React, JavaScript, TypeScript, HTML/CSS, etc.
In a PR the other day, I was checking that a string started with a specific character by doing it the old school way:
const myString = "ABCD";
console.log(myString.indexOf('A') === 0 ? 'It starts with "A"' : 'It does not start with "A"');
During the PR review, a colleague pointed out I could have accomplished the same thing with the "new" .startsWith
method.
const myString = "ABCD";
console.log(myString.startsWith('A') ? 'It starts with "A"' : 'It does not start with "A"');
🤦♂️Clearly both methods do exactly the same thing. The second is only 3 characters shorter. However, it is much more readable. If someone unfamiliar with coding read the first sample, they'd have to figure out what the heck was going on. The second example is much more obvious. What do you know? An old 🐶 can learn new tricks!
There are several other very handy String object methods in ES6. Be sure to check them out as well.
- String.prototype.startsWith
- String.prototype.includes
- String.prototype.endsWith
- String Object for general info
P.S. With all the new .startsWith
, .endsWith
, and .includes
methods, you might want to be sure to compare them using the same case.
const myString = "ABCD";
console.log(myString.toLowerCase().endsWith('d') ? 'It ends with "d or D"' : 'It does not end with "d or D"');