2014.11.17

JavaScript String slice, substr, substring: which to use?

I recently read Douglas Crockford’s JavaScript: The Good Parts. It’s a classic (published in 2008) which is credited with reviving respect for JavaScript as a programming language. Given its title, it’s also famously short.

One very specific thing it cleared up for me was what to do with all of JavaScript’s various substring methods:

One method takes an offset and a length. The other takes two offsets. The names don’t reflect this distinction in any way, so they’re impossible to remember. I resorted to writing an Alfred Snippet with the syntaxes, to quickly look it up (since I always had to).

They also have some other differences in behavior: substring doesn’t allow its offset to be negative, but substr does. This is arbitrary. It’s impossible to remember because there’s no rhyme or reason to it.

Crockford cleared this all up. The solution is to never use either method!

Instead, you should use the slice method:

This takes two offsets. Either can be negative. And it’s the exact same as the corresponding Array slice method.

So: stop using substr and substring. Use slice!

Please leave comments! It's what makes writing worthwhile.

comments powered by Disqus