我有一个字符串:
"some text 0 <span>span 0 </span>some text 1<span>span 1</span>"
我想将其转换为某种结构,例如:
[
{ text: 'some text 0' },
{ span: 'span 0' },
{ text: 'some text 1' },
{ span: 'span 1' }
]
我知道我可以将其强制转换为jquery并使用find获得一个跨度数组,但是有没有办法像上面那样获得一个数组?
谢谢!
答案 0 :(得分:2)
因为jQuery没有用于处理文本节点的非常方便的方法,所以我更喜欢使用内置的Javascript来迭代childNodes
和.map
它们,提取节点的textContent
和tagName
(如果节点是元素)或text
(如果节点是文本节点):
const str = "some text 0 <span>span 0 </span>some text 1<span>span 1</span>";
const doc = new DOMParser().parseFromString(str, 'text/html');
const arr = [...doc.body.childNodes]
.map((node) => ({
[node.nodeType === 3 ? 'text' : node.tagName.toLowerCase()]: node.textContent
}));
console.log(arr);
答案 1 :(得分:1)
使用常规exp,您可以尝试以下操作。
const regex = /([a-zA-Z0-9 ]*)\<span\>([a-z0-9 ]*)\<\/span\>/gm;
const str = `some text 0 <span>span 0 </span>some text 1<span>span 1</span>some<span>span 1</span>`;
let m;
let ar = [];
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
//console.log(`Found match, group ${groupIndex}: ${match}`);
if(groupIndex == 1){
ar.push({"text":match});
}
else if(groupIndex == 2){
ar.push({"span":match});
}
});
}
console.log(ar);