Slicing strings in JS
When I need to get a substring, I usually use one of the following two methods: substring
and substr
. One thing that really bothers me is that the names of these functions are so similar that I almost always have to look them up.
Today, I accidentally wrote string.slice()
in an app because I had just been coding in Python. To my surprise, it worked! I didn’t know you could slice a string and get back a string in JavaScript, just like in Python. I’ve been programming for 15 years and using JavaScript for almost that long, but I wasn’t aware of this. Oof!
Now I have a new favorite way to slice strings in JavaScript—slice()
—which has a less confusing name and is actually much more powerful. Why is it more powerful? Because I can use negative indices!
let name = 'Tuan';
console.log(name.slice(0,1)); // 'T'
console.log(name.slice(1,-1)); // 'ua'