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

Find specific occurrence and parse it into an array.

本文关键字:数组 事件 查找      更新时间:2023-09-26

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

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

  2. 将所有的出现次数输入到数组

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

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

感谢您的帮助,如果我不够详细,请原谅。

您可以使用.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将每个匹配项转换为数字,并截断:$