лучший способ проверить, является ли строка HTML - PullRequest
1 голос
/ 15 апреля 2019

Какой метод лучше всего подходит для проверки, является ли строка html или элементом html, переданным в

это то, что я сейчас использую

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" />');

Ответы [ 2 ]

4 голосов
/ 15 апреля 2019

Использование DOMParser:

function isHTML(string) {
    return Array.from(new DOMParser().parseFromString(string, "text/html").body.childNodes).some(({ nodeType }) => nodeType == 1);
1 голос
/ 15 апреля 2019

Поместите строку в <template>.

Свойство content шаблона возвращает DocumentFragment, которое, в свою очередь, имеет свойство childElementCount

Обратите внимание, что вы также можете вставить DocumentFragmentв любой другой элемент, используя такие методы, как 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)))

Примечание <template> не поддерживается в более старых версиях IE

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...