首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >检查HTML代码片段是否对JavaScript有效

检查HTML代码片段是否对JavaScript有效
EN

Stack Overflow用户
提问于 2012-04-05 18:10:03
回答 6查看 34.2K关注 0票数 36

我需要一个可靠的HTML库/函数来检查JavaScript片段是否有效,以便从我的代码中调用。例如,它应该检查打开的标签和引号是否关闭,嵌套是否正确等。

我不希望验证失败,因为有些东西不是100%标准的(但无论如何都会工作)。

EN

回答 6

Stack Overflow用户

发布于 2012-04-05 18:12:03

好的,下面的代码:

代码语言:javascript
复制
function tidy(html) {
    var d = document.createElement('div');
    d.innerHTML = html;
    return d.innerHTML;
}

这将最大限度地“纠正”格式错误的HTML。如果这对您有帮助,那么它比尝试验证HTML容易得多。

票数 20
EN

Stack Overflow用户

发布于 2015-09-29 13:43:41

代码语言:javascript
复制
function validHTML(html) {
  var openingTags, closingTags;

  html        = html.replace(/<[^>]*\/\s?>/g, '');      // Remove all self closing tags
  html        = html.replace(/<(br|hr|img).*?>/g, '');  // Remove all <br>, <hr>, and <img> tags
  openingTags = html.match(/<[^\/].*?>/g) || [];        // Get remaining opening tags
  closingTags = html.match(/<\/.+?>/g) || [];           // Get remaining closing tags

  return openingTags.length === closingTags.length ? true : false;
}

var htmlContent = "<p>your html content goes here</p>" // Note: String without any html tag will consider as valid html snippet. If it’s not valid in your case, in that case you can check opening tag count first.

if(validHTML(htmlContent)) {
  alert('Valid HTML')
}
else {
  alert('Invalid HTML');
}
票数 3
EN

Stack Overflow用户

发布于 2021-02-12 03:12:10

9年后,使用DOMParser怎么样?

它接受字符串作为参数并返回Document类型,就像HTML一样。因此,当出现错误时,返回的document对象中包含<parsererror>元素。

如果将html解析为xml,至少可以检查html是否符合xhtml。

示例

代码语言:javascript
复制
> const parser = new DOMParser();
> const doc = parser.parseFromString('<div>Input: <input /></div>', 'text/xml');
> (doc.documentElement.querySelector('parsererror') || {}).innerText; // undefined

将其包装为函数

代码语言:javascript
复制
function isValidHTML(html) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, 'text/xml');
  if (doc.documentElement.querySelector('parsererror')) {
    return doc.documentElement.querySelector('parsererror').innerText;
  } else {
    return true;
  }
}

测试上述功能

代码语言:javascript
复制
isValidHTML('<a>hell<B>o</B></a>') // true
isValidHTML('<a href="test.html">hell</a>') // true
isValidHTML('<a href='test.html'>hell</a>') // true
isValidHTML("<a href=test.html>hell</a>")  // This page contains the following err..
isValidHTML('<ul><li>a</li><li>b</li></ul>') // true
isValidHTML('<ul><li>a<li>b</ul>') // This page contains the following err..
isValidHTML('<div><input /></div>' // true
isValidHTML('<div><input></div>' // This page contains the following err..

上面的代码适用于非常简单的html。但是,如果您的html包含一些类似代码的文本;<script><style>等,尽管它是有效的HTML,但您只需要对其进行操作即可进行XML验证

下面的代码将类似代码的html更新为有效的XML语法。

代码语言:javascript
复制
export function getHtmlError(html) {
  const parser = new DOMParser();
  const htmlForParser = `<xml>${html}</xml>`
    .replace(/(src|href)=".*?&.*?"/g, '$1="OMITTED"')
    .replace(/<script[\s\S]+?<\/script>/gm, '<script>OMITTED</script>')
    .replace(/<style[\s\S]+?<\/style>/gm, '<style>OMITTED</style>')
    .replace(/<pre[\s\S]+?<\/pre>/gm, '<pre>OMITTED</pre>')
    .replace(/&nbsp;/g, '&#160;');

  const doc = parser.parseFromString(htmlForParser, 'text/xml');
  if (doc.documentElement.querySelector('parsererror')) {
    console.error(htmlForParser.split(/\n/).map( (el, ndx) => `${ndx+1}: ${el}`).join('\n'));
    return doc.documentElement.querySelector('parsererror');
  }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10026626

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档