Javascript 测试字符串是否为html的最佳方法

Javascript 测试字符串是否为html的最佳方法,javascript,html,css,regex,string,Javascript,Html,Css,Regex,String,测试字符串是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); // g

测试字符串是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" />');
make=函数(a,b){
让name=null;
设el=null;

如果(//i.test(a)){//使用
DOMParser

function isHTML(string) {
    return Array.from(new DOMParser().parseFromString(string, "text/html").body.childNodes).some(({ nodeType }) => nodeType == 1);

使用
DOMParser

function isHTML(string) {
    return Array.from(new DOMParser().parseFromString(string, "text/html").body.childNodes).some(({ nodeType }) => nodeType == 1);
把绳子放进绳子里

模板的
content
属性返回一个值,该值依次具有
childElementCount
属性

请注意,您还可以使用
element.appendChild(fragment)

const-isHTML=(str)=>{
const temp=document.createElement('template');
temp.innerHTML=str;
return!!temp.content.childElementCount;
}
常数strs=[
'没有html字符串',
“字符串中的某些html”,
'所有html字符串将字符串放入一个字符串中

模板的
content
属性返回一个值,该值依次具有
childElementCount
属性

请注意,您还可以使用
element.appendChild(fragment)

const-isHTML=(str)=>{
const temp=document.createElement('template');
temp.innerHTML=str;
return!!temp.content.childElementCount;
}
常数strs=[
'没有html字符串',
“字符串中的某些html”,

'所有html字符串您不能为此使用正则表达式,如中所述。还请注意,如果所讨论的字符串包含任何数量的用户输入,则将其转换为html是不安全的。您不能为此使用正则表达式,如中所述。还请注意,如果所讨论的字符串包含任何数量的用户输入,则将其转换为html是不安全的。