1

What is the best method and that is thorough to test if a string is html or an html element being passed in

this is what I'm using at the moment

make = function(a, b) {
  let name = null;
  let el = null;


  if(/<[a-z][\s\S]*>/i.test(a)) { //<- Is this the best?
    name = a.match(/(\w+)/i)[1];
    el = document.createElement(name);
    // get attributes and apply them
    return el;
  } else if(a == htmlelement) {
     // do something here
  }
}

createNode('<img id="1" data-name="test" src="image_01.jpg" />');
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
ONYX
  • 5,679
  • 15
  • 83
  • 146
  • 1
    You can't use a regex for this, as stated in a [very famous related question](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). Also note that if the string in question contains any amount of user input, it's unsafe to turn it into HTML. – user229044 Apr 15 '19 at 00:33

2 Answers2

4

Use DOMParser:

function isHTML(string) {
    return Array.from(new DOMParser().parseFromString(string, "text/html").body.childNodes).some(({ nodeType }) => nodeType == 1);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

Put the string into a <template>.

The content property of a template returns a DocumentFragment which in turn has a childElementCount property

Note that you can also insert a DocumentFragment into any other element using methods such as element.appendChild(fragment)

const isHTML = (str) => {
  const temp = document.createElement('template');
  temp.innerHTML = str;
  return !!temp.content.childElementCount;
}


const strs = [
  'no html <> string',
  'some html in <span>string</span>',
  '<div>All html <span>string</span</div>'
]

strs.forEach(s => console.log(s, '<-- is html =',  isHTML(s)))

Note <template> not supported in older IE

charlietfl
  • 170,828
  • 13
  • 121
  • 150