100% API-compatible with the slice from Array.Here’s our good friend at last! You probably know slice from arrays, well it’s also available on strings, and the API is exactly the same, which is nifty: there are more than enough APIs to remember, so when we can reuse one… Many good things to say, then: Guessed it? Yup, if the second index is less than the first, they get inverted! What could go wrong?! Sure, it has to be exactly what we intended, just like new Date(2020, 0, -6) lands on Christmas 2019, that makes perfect sense! There’s a Nasty Joke™ if the second argument is less than the first.Indices can’t be negative (no end-of-string confort there).And arguments are indices, which is cool. The name is clear though, I’ll give it that. Then right when you do your most critical deployment ever, bam! The hidden bug. It’s kinda like this parseInt: everybody thinks that yeah, okay, I got this. It also sports a lousy name, truncated haphazardly, which reminds me of the dark early days of PHP ( nl2br, yes, I’m looking at you-and many others). In particular, although it explicitly allows negative indices to start from the end (which is good!), this facet doesn’t work in JScript, the JS engine in Internet Explorer pre-9.0. Not two indices, but one index and one length. It has an unusual signature: substr(index, length).It is in annex B of the spec, which despite being “normative” since ES2015 instead of “informative” earlier, is about the parts of the language and its standard library that were never quite clean and have been actively discouraged, sometimes for a long time (as for substr, it was frowned upon ever since ES3, that’s 1999, folks). You didn’t know? Good for you! It can’t be trusted and is not even handy. …and beyond! (fear not, all 19 are scheduled already)…ĭid you now? Strings have a substr method.Efficiently extracting a substring (this post).Here is the second article of our daily series: “19 nuggets of vanilla JS.” This time we’ll talk about extracting a part of a string, and see there are no less than 3 ways to go about it… but only one should stick with you □ The series of 19Ĭheck out surrounding posts from the series: Cette page est également disponible en français.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |