谁能建议一个简单的方法来做下面的事情?
"this is <mark>just an</mark> example <mark>snippet</mark>"
["this is", "<mark>just an</mark>", "example", "<mark>snippet</mark>" ]
谢谢大家的回答
下面的代码片段涵盖了带有属性的标签
"<b class="highlight">Paradise</b> Lost"
.split(/(<w+s+(?!term).*?>.*?().*?</[a-zA-Z]*>)/g)
.filter((i) => i)
使用正则表达式拆分,但要考虑所有HTML标签和带有属性的web组件,而不仅仅是<mark>
。
function splitHTML (inputString) {
return inputString
.split(/(<[a-zA-Z-](?!term).*?>.*?().*?</[a-zA-Z-]*>)/g)
.filter((i) => i);
}
console.log(splitHTML('this is <mark>just an</mark> example <mark>snippet</mark>'));
上面的代码适用于:
<mark>text</mark>
<my-tooltip>web component</my-tooptip>
<mark class="red">colored text</mark>
按正则表达式分割,这将给你一些空元素。之后可以过滤空元素。
let a = "this is <mark>just an</mark> example <mark>snippet</mark>";
let x = a.split(/( <mark>.*?().*?</mark>)/g); // ['one', '.two', '.three'];
console.log(x.filter( (el) =>el) );
function splitHTML (inputString) {
const result = [];
// 1. Replace a HTML tag with ###<mark> and </mark>###
inputString = inputString.replaceAll('<mark', '###<mark');
inputString = inputString.replaceAll('</mark>', '</mark>###');
// 2. Split on the newly added sign
inputString = inputString.split('###');
// 3. Filter out empty lines and return the result
return inputString.filter((a) => a);
}
console.log(splitHTML('this is <mark>just an</mark> example <mark>snippet</mark>')); // => ['this is ', '<mark>just an</mark>', ' example ', '<mark>snippet</mark>']
尝试使用replace all,它将工作....
<input type="text" id="text" style="width:500px; max-width: 500px;"/>
<script>
const value = "this is <mark>just an</mark> example <mark>snippet</mark>";
var result = "["" + value.replaceAll(" <mark>", "", "<mark>").replaceAll("</mark> ", "</mark>" , "") + ""]";
document.getElementById("text").value = result;
</script>