Home > Article > Web Front-end > How to use JS regular to get HTML elements? JS regular method to get HTML elements
这篇文章主要介绍了JS正则获取HTML元素的方法,结合实例形式分析了JS针对页面HTML元素正则操作相关技巧与注意事项,需要的朋友可以参考下
本文实例讲述了JS正则获取HTML元素的方法。分享给大家供大家参考,具体如下:
var html = $("#summaryTemplate").html(); var imageMath = /<img [^<,>]*(?=target-type=("|')replace("|'))[^/,<,>]*\/>/; var scriptMath = /<script [^<,>]*(?=target-type=("|')replace("|'))[^/,<,>]*><\/script>/; var linkMath = /<link [^<,>]*(?=target-type=("|')replace("|'))[^/,<,>]*\/>/; alert(html.match(imageMath)); var ht="<img src='/11.jpg' target-type='replace' />asf <img src='/12.jpg' target-type='replace' /> <img src='/13.jpg' target-type='replace' />"; ht.match(imageMath)
为什么Math返回的数组不是 多个Img对象,而是
["<img src="/11.jpg" target-type='replace' />", "'", "'"]
不明白。。。。
后来验证是我的错,正则中 有g配置,是否下移至下一个目标。
正确
var attrbuteMath = "(?:\\w+)\\s*(?:=[^{,},<,>]+)"; var srcMath = "src(?:=[^{,},<,>]+)"; var hrefMath = "href(?:=[^{,},<,>]+)"; var scriptMath = "<script\\s+(?:" + attrbuteMath + ")*><\/script>"; var ge = new RegExp(scriptMath,"gi"); // var html = "<script asdfsadf='asdfsaf' asf=aaadsdfsdf style='' src='' ><\/script>asdfsaf<script asdfsadf='asdfsaf' asf=''aa adsdfsdf ><\/script>"; var html = $("#txtHtml").val(); var result = ge.exec(html); alert(result);
g表示要搜索字符串出现的,而不是找到第一个匹配后就停止。如果还要模式不区分大小写,可以给第二个参数添加字符 i
The above is the detailed content of How to use JS regular to get HTML elements? JS regular method to get HTML elements. For more information, please follow other related articles on the PHP Chinese website!