查找特定事件并将其解析为数组。

时间:2015-10-06 18:10:06

标签: javascript jquery parsing screen-scraping

我在var中有一堆杂乱无章的信息,我想:

  1. 循环显示信息并提取前面带有货币符号$或单词Price的所有数字。

  2. 将所有这些事件输入数组

  3. 到目前为止,我找到了一种方法来查找美元符号的出现,但我不知道我必须采取的其他步骤。

    var str = "My father/taughtme$500ho<div>wtoPrice:700throwabaseball$30";
    var getCount=function(str){
        return (str.match(/$/g) || []).length;
    };
    alert(getCount(str));
    

    感谢任何帮助,如果我不够详细,请对不起。

1 个答案:

答案 0 :(得分:1)

您可以使用.match和正则表达式完成此操作。

var data = "My father/taughtme$500ho<div>wtoPrice:700throwabaseball$30";

var prices = (data.match(/[\$|price:]\d+/gi) || []).map(function(m) {
  //Convert each match to a number
  return +m.substring(1);
});

document.write(prices);
console.log(prices);

在任何情况下,表达式/[\$|price:]\d+/gi都会匹配以$price:开头的所有数字。然后,使用map将每个匹配转换为数字,然后切断:$