I want to check if the first item from the string is wrapped in HYML tags. I can have the next situations:
"nothtml <p>" // expect false"<p> " //expect true" <p> " //expect true"<span>text " //expect true
const s = '<p>test <p>';
console.log(s.split('<'))
console.log(/<\/?[a-z][\s\S]*>/i.test(s[0]));
According to the above idea, i want to split() the string and to get the first element, but i can't manage all situations when the first item could be not only <p>, but also <span>, <div>, how you can notice the length of the html tag can be different. Basically i need to find a solution to split the elements that are wrapped in tags <element>. How to do that?
Here is the approach I suggested in the comments, namely to parse text as HTML and inspect the first node. This example assumes a browser environment but there are HTML parsers available for Node.js as well. It also assumes that the input can be parsed as HTML.
function isWrapped(text) {
const container = document.createElement('div');
container.innerHTML = text.trimStart();
return container.childNodes[0]?.nodeType === Node.ELEMENT_NODE;
}
console.log(isWrapped('foo <p>test</p>'));
console.log(isWrapped('<p>test</p>'));
console.log(isWrapped('<p'));
You can use regular expressions to test your string.
See below regex, it checks if it's starting with HTML tag element with ignoring any space before the tag
/^\s*(\<\w+\>[\s\S]*\<\/\w+\>)/.test("nothtml <p>") // return false
and if you want to get the element
/^\s*(\<\w+\>[\s\S]*\<\/\w+\>)/.exec(" <element>dsa</element>")[1]
feel free to update the regular expression based on your needs, there are plenty of examples over the internet of how to validate HTML string using regular expressions.