Home > Web Front-end > JS Tutorial > How to use JS regular to get HTML elements? JS regular method to get HTML elements

How to use JS regular to get HTML elements? JS regular method to get HTML elements

零下一度
Release: 2017-04-21 11:51:56
Original
1875 people have browsed it

这篇文章主要介绍了JS正则获取HTML元素的方法,结合实例形式分析了JS针对页面HTML元素正则操作相关技巧与注意事项,需要的朋友可以参考下

本文实例讲述了JS正则获取HTML元素的方法。分享给大家供大家参考,具体如下:


var html = $("#summaryTemplate").html();
var imageMath = /<img [^<,>]*(?=target-type=("|&#39;)replace("|&#39;))[^/,<,>]*\/>/;
var scriptMath = /<script [^<,>]*(?=target-type=("|&#39;)replace("|&#39;))[^/,<,>]*><\/script>/;
var linkMath = /<link [^<,>]*(?=target-type=("|&#39;)replace("|&#39;))[^/,<,>]*\/>/;
alert(html.match(imageMath));
var ht="<img src=&#39;/11.jpg&#39; target-type=&#39;replace&#39; />asf   <img src=&#39;/12.jpg&#39; target-type=&#39;replace&#39; />        <img src=&#39;/13.jpg&#39; target-type=&#39;replace&#39; />";
ht.match(imageMath)
Copy after login

为什么Math返回的数组不是 多个Img对象,而是


["<img src="/11.jpg" target-type=&#39;replace&#39; />", "&#39;", "&#39;"]
Copy after login

不明白。。。。

后来验证是我的错,正则中 有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=&#39;asdfsaf&#39; asf=aaadsdfsdf style=&#39;&#39; src=&#39;&#39; ><\/script>asdfsaf<script asdfsadf=&#39;asdfsaf&#39; asf=&#39;&#39;aa adsdfsdf  ><\/script>";
var html = $("#txtHtml").val();
var result = ge.exec(html);
alert(result);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template