Can anyone suggest a simple* way to do the following?
"this is <mark>just an</mark> example <mark>snippet</mark>"
to
["this is", "<mark>just an</mark>", "example", "<mark>snippet</mark>" ]
Thanks for the answer guys
this snippet below covers tags with attributes also
"<b class="highlight">Paradise</b> Lost"
.split(/(<\w+\s+(?!term).*?>.*?().*?<\/[a-zA-Z]*>)/g)
.filter((i) => i)
Split using regex, but considering all HTML tags and web components with attributes, not just <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>'));
The code above will work for:
<mark>text</mark><my-tooltip>web component</my-tooptip><mark class="red">colored text</mark>Just split by regex, that will give you some empty elements.. you can filter empty elements afterwards.
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>']