jQuery在0级获取文本数组

时间:2018-11-29 05:52:45

标签: jquery

我有一个字符串:

  "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获得一个跨度数组,但是有没有办法像上面那样获得一个数组?

谢谢!

2 个答案:

答案 0 :(得分:2)

因为jQuery没有用于处理文本节点的非常方便的方法,所以我更喜欢使用内置的Javascript来迭代childNodes.map它们,提取节点的textContenttagName(如果节点是元素)或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);