Skip to content

一个正则匹配问题引起的思考 #26

@shiiiiiiji

Description

@shiiiiiiji

image

今天在群里一位妹子提出一个问题,说是想“使用正则匹配服务端返回的数据”(如上图所示).

具体返回数据如下:

const content = '<div class="MN_gusList" style="box-sizing: border-box; color: rgb(0, 140, 238); cursor: pointer; font-family: &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px;"><span style="box-sizing: border-box;">1.<span>&nbsp;</span></span><span class="MN_guideQue" id="biguiyuan" sid="6" style="box-sizing: border-box; transition: all 0.2s ease-in-out;" data-qaId="b9ae933b-0d13-455d-b6b6-0e7beef59f0d" data-title="测试问题类型勿删" data-qaType="3">别名1</span></div>'

从中取出这几个值:data-qaIddata-qaTypedata-title以及文本。

image

其实,这个需求在前端业务中挺常见的,我的第一反应也是正则,大概是下面这样:

/data-qaId=\"([^\"]*)\"/
/data-qaType=\"([^\"]*)\"/
/data-title=\"([^\"]*)\"/
/\>([^\<]*)\<\/span\>\<\/div\>/

从上之下分别匹配data-qaIddata-qaTypedata-title以及文本的值。

另外,一位大佬给出了使用querySelector的方案,我的第一反应是这个不应该是数据需要渲染在页面上,然后通过 API 取出得到节点对象,其实我的认识狭隘了,我们知道其实querySelector本质上是 JS 对象的一个方法,而这个对象就是节点对象,我们完全可以通过 原生的 JS API 创建一个节点对象,而且并不需要将他添加到页面中就可以方便的利用 JS 的一些原生或者其他方法了。实现如下:

const domObj = document.createElement('div');

domObj.innerHTML = '<div class="MN_gusList" style="box-sizing: border-box; color: rgb(0, 140, 238); cursor: pointer; font-family: &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px;"><span style="box-sizing: border-box;">1.<span>&nbsp;</span></span><span class="MN_guideQue" id="biguiyuan" sid="6" style="box-sizing: border-box; transition: all 0.2s ease-in-out;" data-qaId="b9ae933b-0d13-455d-b6b6-0e7beef59f0d" data-title="测试问题类型勿删" data-qaType="3">别名1</span></div>';

const target = domObj.querySelector('#biguiyuan');
console.log(domObj.querySelector('#biguiyuan').getAttribute('data-qaid'), domObj.querySelector('#biguiyuan').getAttribute('data-title'), domObj.querySelector('#biguiyuan').getAttribute('data-qatype'), domObj.querySelector('#biguiyuan').innerText);

这样实现比正则来做准确度更高,而且不容易出 Bug。

思路很重要哇。

而且其实前端里有很多做法都是“借鉴”别人的,很多前端包括我,都是拿来主义,其实就是很少去思考技术原理。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions