JavaScript:解析此字符串

问题描述 投票:0回答:4

这里是一个很长的字符串(实际上是一个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。

javascript html json text-parsing
4个回答
0
投票
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;
}

0
投票

这就是字符串:

   '<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方法来获取你想要的值


0
投票

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}

0
投票

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

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

var parsedHTML = $(badgeHTML); // Returns a jQuery collection of HTML nodes
© www.soinside.com 2019 - 2024. All rights reserved.