javascripthtmljsontext-parsing

JavaScript: Parse this string


Here is a long string (actually a JSON key value):

"\u003cspan title=\"5 gold badges\"\u003e\u003cspan class=\"badge1\"\u003e●\u003c/span\u003e\u003cspan class=\"badgecount\"\u003e5\u003c/span\u003e\u003c/span\u003e\u003cspan title=\"8 silver badges\"\u003e\u003cspan class=\"badge2\"\u003e●\u003c/span\u003e\u003cspan class=\"badgecount\"\u003e8\u003c/span\u003e\u003c/span\u003e\u003cspan title=\"57 bronze badges\"\u003e\u003cspan class=\"badge3\"\u003e●\u003c/span\u003e\u003cspan class=\"badgecount\"\u003e57\u003c/span\u003e\u003c/span\u003e"

I need a way to parse it to get the number of gold, silver and bronze badges, using simple JScript in Dashcode.


Solution

  • function getBadgeCounts(s) {
      var badgeCountRE = /title="(\d+)/g, match = null, counts = [];
      while ((match = badgeCountRE.exec(s)) !== null) {
        counts.push(match[1]);
      }
      return {gold: counts[0], silver: counts[1], bronze: counts[2]};
    }
    

    Without hardcoded medal names:

    function getBadgeCounts(s) {
      var badgeCountRE = /title="(\d+) (\w+)/g, match = null, counts = {};
      while ((match = badgeCountRE.exec(s)) !== null) {
        counts[match[2]] = match[1];
      }
      return counts;
    }