这里是一个很长的字符串(实际上是一个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。
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;
}
这就是字符串:
'<span title="5 gold badges">
<span class="badge1">●</span>
<span class="badgecount">5</span>
</span>
<span title="8 silver badges">
<span class="badge2">●</span>
<span class="badgecount">8</span>
</span>
<span title="57 bronze badges">
<span class="badge3">●</span>
<span class="badgecount">57</span>
</span>'
也许你可以将它添加到一个不可见的div中,这样你就可以使用DOM方法来获取你想要的值
var str = "\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";
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}
如果将该字符串放入 jQuery 调用中,则可以像查询任何其他 HTML 片段一样查询文档片段:
var badgeHTML = "..." // Your encoded string here
var parsedHTML = $(badgeHTML); // Returns a jQuery collection of HTML nodes