Article 184Q9 CodeSOD: You Can't Always Count on Regular Expressions

CodeSOD: You Can't Always Count on Regular Expressions

by
Mark Bowytz
from The Daily WTF on (#184Q9)

After spending the most of the afternoon searching, trying to solve a rather vexing issue, Adam found exactly the solution he was looking for and wanted to squirrel it away for later reference.

Sure - he could have added to "Favorites" in his browser like on every other website in the world, but there was something about the "bookmark" button on this particular site that called to him. It was more than a dumb link, it was a counter telling you how many people had bookmarked a resource, and you could bookmark it yourself.

Also, it was the most calming shade of blue.

before.png

Blame exhaustion, blame frustration, or even the fact that his remaining brain cells were delighted to see that 26 other souls had found this page bookmark-worthy - Adam threw caution to the wind, risked a stealth malware install and clicked on it.

The thing was, instead of increasing by 1 as anyone would expect, it did so by 10.

after.png

"Shenanigans!" Adam shouted as he got to work, digging into the page's source and found the code responsible. (After all, who would be so sneaky that they'd increment a bookmark counter by an artificial amount just to make it seem like the page had been bookmarked more than it actually was?)

As it turned out - the original coder, not knowing that you could extract the contents of an HTML node with the "text()" method, or similar ones, decided to give regular expressions a try.

updateBookmarkCounter = (upOrDown) ->counterSpan = $('.bookmark .counter')spanHtml = counterSpan.html()count = spanHtml.match(/\d/).first().toInteger()newCount = if (upOrDown == 'down') then (count - 1) else (count + 1)newCount = 0 if newCount < 1 counterSpan.html(spanHtml.replace(/\d/, newCount)) updateUserBookmarkCount upOrDown

While it was an interesting execution, little did the site's author know that once you hit more than 9 bookmark clicks, "/\d/" was only going to match the first digit of the total count.

proget-icon.png [Advertisement] Universal Package Manager - store all your Maven, NuGet, Chocolatey, npm, Bower, TFS, TeamCity, Jenkins packages in one central location. Learn more today! TheDailyWtf?d=yIl2AUoC8zA3s9_uyGja_w
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments