Home  >  Article  >  Web Front-end  >  javascript 如何判断字符串中是否有html代码/标签

javascript 如何判断字符串中是否有html代码/标签

WBOY
WBOYOriginal
2016-06-01 09:54:304373browse

javascript 判断字符串中是否有html代码/标签,我们可以使用javascript的正则表达式来实现,代码如下:

<code class="language-javascript">/**
 * 字符串是否含有html标签的检测
 * @param htmlStr
 */
function checkHtml(htmlStr) {
    var  reg = /]+>/g;
    return reg.test(htmlStr);
}</code>

这个js函数就可以直接判断字符串中是否有html标签。下面来看一下如何使用这个函数。

使用实例:

hrml代码:

<code class="language-html"><div id="box">
        sdfsdf
        <div></div>
        <span>sdfsdf</span>
</div></code>

js代码: 

<code class="language-javascript">/**
 * 字符串是否含有html标签的检测
 * @param htmlStr
 */
function checkHtml(htmlStr) {
    var  reg = /]+>/g;
    return reg.test(htmlStr);
}
window.onload=function(){
    var html=document.querySelector('#box').innerHTML;
    alert(checkHtml(html))
}</code>

本文章的js/html/php/css代码均可以复制到这个页面进行在线调试,你不妨试一下。

http://www.manongjc.com/runcode

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn