A different view of strings
If you use jQuery, I’m betting at some point you’ve needed to extract the database ID associated with an HTML element (e.g. <div id="customer_123">...</div>). How many times have you written code like this?
$("div").click(function() {
var attrValue = $(this).attr("id");
var id = attrValue.substr(attrValue.indexOf("_")+1);
// do something with the id
});
This seemed like a perfectly reasonable approach to me for the longest time. While looking through the source of another site though, I saw something I hadn’t ever seen before. Apparently, JavaScript has a regex literal syntax that shortens the code above to the following:
$("div").click(function() {
var id = $(this).attr("id").split(/_/)[1];
// do something with the id
});
You don’t have to use the regex literal, a character or string will work too. Neither method is exceptionally readable, so I prefer to the shorter version. Either way works, so if you like one more than the other, use that. I’m not sharing this tip though because it’s novel though.
The reason I bring this up is because it demonstrated to me a totally different way of thinking about a really trivial problem. I saw a string of text like “edit_123” as a string to be parsed and the author of the code I learned this technique from viewed that string as a data structure with two parts. There’s a profound difference in thinking there.




