JavaScript:解析此字符串

时间:2011-04-07 14:27:19

标签: javascript text-parsing

这是一个长字符串(实际上是一个JSON键值):

"\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"

我需要一种方法来解析它以获得金色,银色和铜色徽章的数量,在Dashcode中使用简单的JScript。

4 个答案:

答案 0 :(得分:1)

这就是字符串:

   '<span title="5 gold badges">
        <span class="badge1">&#9679;</span>
        <span class="badgecount">5</span>
    </span>
    <span title="8 silver badges">
        <span class="badge2">&#9679;</span>
        <span class="badgecount">8</span>
   </span>
   <span title="57 bronze badges">
       <span class="badge3">&#9679;</span>
       <span class="badgecount">57</span>
   </span>'

也许你可以将它添加到一个不可见的div,所以你可以使用DOM方法来获得你想要的值

答案 1 :(得分:1)

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]};
}

没有硬编码的奖牌名称:

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;
}

答案 2 :(得分:1)

如果将该字符串放入jQuery调用中,则可以像查看任何其他HTML一样查询文档片段:

var badgeHTML = "..." // Your encoded string here

var parsedHTML = $(badgeHTML); // Returns a jQuery collection of HTML nodes

答案 3 :(得分:1)

var str = "\u003cspan title=\"5 gold badges\"\u003e\u003cspan class=\"badge1\"\u003e&#9679;\u003c/span\u003e\u003cspan class=\"badgecount\"\u003e5\u003c/span\u003e\u003c/span\u003e\u003cspan title=\"8 silver badges\"\u003e\u003cspan class=\"badge2\"\u003e&#9679;\u003c/span\u003e\u003cspan class=\"badgecount\"\u003e8\u003c/span\u003e\u003c/span\u003e\u003cspan title=\"57 bronze badges\"\u003e\u003cspan class=\"badge3\"\u003e&#9679;\u003c/span\u003e\u003cspan class=\"badgecount\"\u003e57\u003c/span\u003e\u003c/span\u003e";

var res = {
    gold: 0,
    silver: 0,
    bronze: 0
};

/* using a RexExp
/                    - delimeter
(\d+)                - capturing one or more digits
\s+                  - one or more whitespace characters
(gold|silver|bronze) - capturing the color
/g                   - delimeter (global flag)

to match the information in the title of the spans
and using the replace trick to populate res
*/

str.replace( /(\d+)\s+(gold|silver|bronze)/g, function( all, count, color ) {
    res[color] += parseInt( count );
});

console.log( res ); // Object { gold=5, silver=8, bronze=57}