将 Html 字符串解析为特定数组,而无需使用 DOM 解析器


let data = "<p>Size: 5 cm</p><p>Weight: 30 g</p><p>Allows you to collect your hair easily.</p><p><br />Holds your hair, does not come out.</p><p>No more fussing with rubber buckles.</p>";

我的目标是创建一个属性数组。 属性表示尺寸、重量等

result = [{Size: "5 cm"}, {Weight: "30 g"}]

请让我知道使用javascript的脚本

不确定这是否是最有效的方法,但这是我设法做到的。

let data = "<p>Size: 5 cm</p><p>Weight: 30 g</p><p>Allows you to collect your hair easily.</p><p><br />Holds your hair, does not come out.</p><p>No more fussing with rubber buckles.</p>";
// regex to match content between the tags
const regex = /(?<=>)(.*?)(?=<)/g;
// found matches stored in array
let found = data.match(regex);
// final result will be stored here
let newData = {};
// removes empty strings
found = found.filter(item => item);
// check if index contains ":" then splits it and stores in a dictionary
for(let i=0; i<found.length; i++){
if(found[i].includes(":")){
let temp = found[i].split(':');
newData[temp[0].trimStart()] = temp[1].trimStart();
}
}
console.log(newData);

这是一个快速简单的函数,它使用一系列指标来查找

let data = "<p>Size: 5 cm</p><p>Weight: 30 g</p><p>Allows you to collect your hair easily.</p><p><br />Holds your hair, does not come out.</p><p>No more fussing with rubber buckles.</p>";
let metrics = ['Size', 'Weight']
const result = Object.assign(...metrics.map(m =>  data.split(m)[1].split("</p>")[0]).map((m, i) => ({[metrics[i]]: m.replace(':', '').trim()})))
console.log(result);

您可以使用一个正则表达式来解决此问题,该表达式搜索包含">标签:数字单位"的所有段落

正则表达式可能是这样的:/<p>([^:]+)s*:s*([d.]+s+w+)</p>/g
在这里测试它:https://regex101.com/r/Q3ng6U/1/

解释:

  • <p>搜索开头段落。如果您认为它们可以具有某些属性,例如样式id,class,那么您可以将其替换为<p[^>]*>其中[^>]表示任何不是">"的字符,而*表示重复零次或多次。

  • ([^:]+)用于捕获标签。它查找任何不是重复一次或多次分号的字符。

  • s*表示空格、制表符等,零次或多次。

  • :s*表示分号字符后跟一些可选空格。

  • [d.]+表示数字和点,至少一次。这是因为您可能有类似">1.3 m"的东西。

  • ([d.]+s+w+)将捕获数量和单位,但前提是它被一个矿石几个空格隔开。如果您认为您可以使用"20 公斤"而不是"20 公斤",请将s+替换为s*.但是您可能需要再次拆分它以重新注入空间,以便所有属性都具有相同的外观。

  • </p>是服装段落标签。斜杠被转义,因为它用于分隔正则表达式的开头和结尾。

  • 末尾的g标志使正则表达式搜索所有匹配项,而不仅仅是在第一个匹配项上停止。

现在,对于JavaScript代码,您可以执行以下操作:

const regex = /<p>([^:]+)s*:s*([d.]+s+w+)</p>/g;
const data = `<p>Packet width: 20 cm</p><p>Weight: 1.2 kg</p><p>Allows you to collect your hair easily.</p><p><br />Holds your hair, does not come out.</p><p>No more fussing with rubber buckles.</p>`;
let match;
let properties = [];
while ((match = regex.exec(data)) !== null) {
// As a label could be several words but a JS object propery cannot have them
// we'll just replace all consequent invalid chars by underscores.
let label = match[1].replace(/W+/g, '_').toLowerCase();;
// Create an object so that we can add the property from the corrected label.
let entry = {};
entry[label] = match[2];
// Put this object in the array of properties found.
properties.push(entry);
}
console.log(properties);

这将用以下内容填充属性

[
{packet_width: "20 cm"},
{weight: "1.2 kg"}
]

最新更新