美文网首页
js 匹配URL的正则表达式

js 匹配URL的正则表达式

作者: _不能说的秘密i | 来源:发表于2020-03-18 02:37 被阅读0次
  • 待匹配的字符串
const str = `<div>
    <a href="https://www.baidu.com">百度</a>
    <a href="http://www.qq.com">QQ</a>
    <a href="https://www.sina.com">新浪</a>
    <div>
        <img src="https://www.sina.com/1.jpg" alt="">
        <img src="http://www.qq.com/2.png" alt="">
        <img src="https://www.sina.com/3.png" alt="">
    </div>
</div>`;

获取字符串中所有 a 标签的 href 的值及其中间的文本内容

const linkReg = /(<a.*href[\s]?=[\s]?['"](.*)['"].*?>(.*)<\/a>)/igm;
const linkArray = [];
str.replace(linkReg, (...args) => linkArray.push({ href: args[1], text: args[2] }));
console.log(linkArray);

输出结果:

[
    {
        "href": "https://www.baidu.com",
        "text": "百度"
    },
    {
        "href": "https://www.qq.com",
        "text": "QQ"
    },
    {
        "href": "https://www.sina.com",
        "text": "新浪"
    }
]

匹配所有的 img 标签的 src 的值

const imgArray = [];
const imgReg = /(<img.*src[\s]?=[\s]?['"](.*?)['"].*\/?>)/igm;
str.replace(imgReg, (...args) => imgArray.push(args[2]));

//  ---- 或者  ----
const imgArray2 = [];
let match = null;
do {
    match = imgReg.exec(str);
    match && imgArray2.push(match[2]);
} while (match);

//  两种方式的结果是一样的
console.log(imgArray);
console.log(imgArray2);

输出结果:

[
    "https://www.sina.com/1.jpg",
    "https://www.qq.com/2.png",
    "https://www.sina.com/3.png"
]

匹配出所有的字符串中所有的URL, 不区分html标签

const urlReg = /(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/ig;
const urlArrray = str.match(urlReg);

输出结果:

[
    "https://www.baidu.com",
    "https://www.qq.com",
    "https://www.sina.com",
    "https://www.sina.com/1.jpg",
    "https://www.qq.com/2.png",
    "https://www.sina.com/3.png"
]

相关文章

  • url正则 有测试用例

    js匹配网址url的正则表达式集合 方法 测试

  • Fiddler 代理文件夹和文件

    代理文件 匹配生产URL正则表达式 regex:http://www.a.com/statics/js/(.*)[...

  • nginx中location指令说明

    该指令用于匹配URL 语法如下: = :用于不含正则表达式的 url 前,要求请求字符串与 url 严格匹配,如果...

  • [Emacs] 自动切换语言模式

    打开js文件时,自动切换到js2-mode 其中“\\.js\\'”是正则表达式用来匹配js文件,“\\.”匹配“...

  • 前端开发之JS(正则)

    js正则表达式 电话号码的匹配 /13566668888/.test(value) 完全匹配 /^13566668...

  • js 匹配URL的正则表达式

    待匹配的字符串 获取字符串中所有 a 标签的 href 的值及其中间的文本内容 输出结果: 匹配所有的 img 标...

  • 正则表达式

    js正则表达式总结 正则表达式的字符匹配量词横向模糊匹配var regex = /ab{2,5}/gg 表示全局匹...

  • 2018-09-15

    正则表达式的区别 JS中语法: /匹配对象的模式/

  • JS常用各种正则表达式

    原文链接 匹配url 这个url的正则表达式判断的JavaScript!比较全面的。它验证的情况包括IP,域名(d...

  • Flutter 获取 Url 域名

    Flutter 截取url 的域名 两种方式 1 通过正则匹配截取 通过正则表达式截取匹配的域名 2 通过Flut...

网友评论

      本文标题:js 匹配URL的正则表达式

      本文链接:https://www.haomeiwen.com/subject/vhmfyhtx.html