首页 > 解决方案 > javascript检查字符串是否仅包含html

问题描述

这是我的字符串

<img class="img" src="a.png"><img class="img" src="a.png"><img class="img" src="a.png"> 

我想检查字符串是否只包含 html 标签

dwd<img class="img" src="a.png">dwd<img class="img" src="a.png"><img class="img" src="a.png"> dwd

如果包含类似上面示例的任何字符串,我想返回 false

我这里有一些代码可以检查一下

function isHTML(str) {
  var a = document.createElement('div');
  a.innerHTML = str;

  for (var c = a.childNodes, i = c.length; i--; ) {
    if (c[i].nodeType == 1) return true; 
  }

  return false;
}


isHTML('<a>this is a string</a>') // true
isHTML('this is a string')        // false
isHTML('this is a <b>string</b>') // true

正如我们在第三个示例中看到的那样,它返回 true 并且有一些带有 html 标签的字符串,所以如果只有 html 标签,我如何编辑它并使其返回 true 无文本

这里有另一种方法,但上面相同

var isHTML = RegExp.prototype.test.bind(/(<([^>]+)>)/i);

isHTML('Testing');               // false
isHTML('<p>Testing</p>');        // true
isHTML('<img src="hello.jpg">'); // true
isHTML('My <p>Testing</p> string');   // true (caution!!!)
isHTML('<>');                    // false

它的好方法但是isHTML('My <p>Testing</p> string'); // true (caution!!!)

在这里我想返回 false 因为有一些带有 html 标签的字符串

标签: javascript

解决方案


选项 1:使用 RegExp 和字符串替换:

const isHTML = (str) => !(str || '')
  // replace html tag with content
  .replace(/<([^>]+?)([^>]*?)>(.*?)<\/\1>/ig, '')
  // remove remaining self closing tags
  .replace(/(<([^>]+)>)/ig, '')
  // remove extra space at start and end
  .trim();

console.log(isHTML('Testing'));                         // false
console.log(isHTML('<p>Testing</p>'));                  // true
console.log(isHTML('<img src="hello.jpg">'));           // true
console.log(isHTML('My <p>Testing</p> string'));        // false
console.log(isHTML('<p>Testing</p> <p>Testing</p>'));   // true
console.log(isHTML('<>'));                              // false
console.log(isHTML('<br>'));                            // true

选项 2:使用 DOM API

const isHTML = (str) => {
  const fragment = document.createRange().createContextualFragment(str);
  
  // remove all non text nodes from fragment
  fragment.querySelectorAll('*').forEach(el => el.parentNode.removeChild(el));
  
  // if there is textContent, then not a pure HTML
  return !(fragment.textContent || '').trim();
}

console.log(isHTML('Testing'));                         // false
console.log(isHTML('<p>Testing</p>'));                  // true
console.log(isHTML('<img src="hello.jpg">'));           // true
console.log(isHTML('My <p>Testing</p> string'));        // false
console.log(isHTML('<p>Testing</p> <p>Testing</p>'));   // true
console.log(isHTML('<>'));                              // false
console.log(isHTML('<br>'));                            // true


推荐阅读