This post originally appeared on Viget’s Inspire blog.
Here are two quick tips gleaned from the wiki.
indexOf to test presence
This piece of code will set a variable to a value that evaluates to true or false depending on the presence or absence of a string (your needle) in another string (your haystack).
has_my_name = "Most times, Jason knows what he's doing.".indexOf( "Jason" ) >= 0;
has_my_name = ~"Most times, Jason knows what he's doing.".indexOf( "Jason" );
The first line (the traditional method) sets
true. The second, shorter, line sets
has_my_name to -13 which, being non-zero, would also evaluate to
I’m not entirely sure why the returned index is negative, but it works. Chris Jones unearthed this article on the tilde that more-or-less clarifies what the tilde is doing. Thanks, Chris!
Update: In Elliot’s comment, he rightly notes that separating the equals and tilde works and is less obscure than
=~. I’ve updated the example accordingly.
.link String method
.link String method.
anchor = '<a href="' + url + ">' + text + '</a>';
anchor = text.link( url );
The first line is the string-concatenating method of building anchor elements with which we’re all familiar. The second line is the new hotness. Turns out, though, that it’s actually the old hotness:
.link has been available to us since IE 3.0 and Netscape 2.0. If I’d known then what I know now…