我有以下html。我想用<span>
标签将其分割。
let storyHtml = "<span>People</span> born in different ages are different from each other in various aspects. The world is changing at <span>a</span> rapid pace and thus the difference between <span>people</span> born in different times is inevitable.";
let allSplitPart = storyHtml.split(/<span>.*?<\/span>/gim);
let allMatchPart = storyHtml.match(/<span>.*?<\/span>/gim);
// Output 1: ["", " born in different ages are different from each other in various aspects. The world is changing at ", " rapid pace and thus the difference between ", " born in different times is inevitable."]
//Output 2: ["<span>People</span>", "<span>a</span>", "<span>people</span>"]
我想要什么输出:
["<span>People</span>", " born in different ages are different from each other in various aspects. The world is changing at ","<span>a</span>"," rapid pace and thus the difference between ","<span>people</span>", " born in different times is inevitable."]
答案 0 :(得分:1)
只需将正则表达式的<span>.*?<\/span>
放在()
内,即可将其包括在内。
let storyHtml = "<span>People</span> born in different ages are different from each other in various aspects. The world is changing at <span>a</span> rapid pace and thus the difference between <span>people</span> born in different times is inevitable.";
console.log(storyHtml.split(/(<span>.*?<\/span>)/i).filter(Boolean));
filter(Boolean)
删除如果字符串以跨度开头或结尾或两个跨度之间没有任何文本的情况下出现的空字符串。