检查字符串是否为html [英] Check if a string is html or not

查看:211
本文介绍了检查字符串是否为html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,我想检查它是否是一个HTML。我正在使用正则表达式,但没有得到正确的结果。

I have a certain string for which I want to check if it is a html or not. I am using regex for the same but not getting the proper result.

我验证了我的正则表达式并且它工作正常这里

I validated my regex and it works fine here.

var htmlRegex = new RegExp("<([A-Za-z][A-Za-z0-9]*)\b[^>]*>(.*?)</\1>");
return htmlRegex.test(testString);

这是小提琴,但正则表达式没有在那里运行。 http://jsfiddle.net/wFWtc/

Here's the fiddle but the regex isn't running in there. http://jsfiddle.net/wFWtc/

在我的机器上,代码运行正常但我得到一个假而不是真的结果。
这里缺少什么?

On my machine, the code runs fine but I get a false instead of true as the result. What am missing here?

推荐答案

用于检查字符串是否为HTML的更好的正则表达式是:

A better regex to use to check if a string is HTML is:

/^/

例如:

/^/.test('') // true
/^/.test('foo bar baz') //true
/^/.test('<p>fizz buzz</p>') //true

实际上,它非常好,它会为每个返回 true em>字符串传递给它,这是因为 每个字符串都是HTML 。说真的,即使格式不好或无效,它仍然是HTML。

In fact, it's so good, that it'll return true for every string passed to it, which is because every string is HTML. Seriously, even if it's poorly formatted or invalid, it's still HTML.

如果你要找的是HTML元素的存在,而不是简单的任何文本内容,您可以使用以下内容:

If what you're looking for is the presence of HTML elements, rather than simply any text content, you could use something along the lines of:

/<[a-z][\s\S]*>/i.test()

它无法帮助您以任何方式解析HTML,但它肯定会将字符串标记为包含HTML元素。

It won't help you parse the HTML in any way, but it will certainly flag the string as containing HTML elements.

这篇关于检查字符串是否为html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆