const escapeRegexp = new RegExp(`[${Object.keys(escapeMaps).join('')}]`, 'g')return string.replace(escapeRegexp, (match) => `&${escapeMaps[match]};`)}console.log(escape(`<div><p>hello world</p></div>`))/*<div><p>hello world</p></div>*/8. 取消转义 HTML
const unescape = (string) => {const unescapeMaps = {'amp': '&','lt': '<','gt': '>','quot': '"','#39': "'"}const unescapeRegexp = /&([^;]+);/greturn string.replace(unescapeRegexp, (match, unescapeKey) => {return unescapeMaps[ unescapeKey ] || match})}console.log(unescape(`<div><p>hello world</p></div>`))/*<div><p>hello world</p></div>*/9. 24小时制比赛时间
请判断时间是否符合24小时制 。匹配规则如下:
01:14
1:14
1:1
23:59
const check24TimeRegexp = /^(?:(?:0?|1)d|2[0-3]):(?:0?|[1-5])d$/console.log(check24TimeRegexp.test('01:14')) // trueconsole.log(check24TimeRegexp.test('23:59')) // trueconsole.log(check24TimeRegexp.test('23:60')) // falseconsole.log(check24TimeRegexp.test('1:14')) // trueconsole.log(check24TimeRegexp.test('1:1')) // true10.匹配日期格式
请匹配日期格式,例如(yyyy-mm-dd、yyyy.mm.dd、yyyy/mm/dd),例如 2021–08–22、2021.08.22、2021/08/22 。
const checkDateRegexp = /^d{4}([-./])(?:0[1-9]|1[0-2])1(?:0[1-9]|[12]d|3[01])$/console.log(checkDateRegexp.test('2021-08-22')) // trueconsole.log(checkDateRegexp.test('2021/08/22')) // trueconsole.log(checkDateRegexp.test('2021.08.22')) // trueconsole.log(checkDateRegexp.test('2021.08/22')) // falseconsole.log(checkDateRegexp.test('2021/08-22')) // false11. 匹配十六进制颜色值
请从字符串中获取十六进制颜色值 。
const matchColorRegex = /#(?:[da-fA-F]{6}|[da-fA-F]{3})/gconst colorString = '#12f3a1 #ffBabd #FFF #123 #586'console.log(colorString.match(matchColorRegex))// [ '#12f3a1', '#ffBabd', '#FFF', '#123', '#586' ]12. 检查URL的前缀是HTTPS还是HTTP
const checkProtocol = /^https?:/console.log(checkProtocol.test('https://medium.com/')) // trueconsole.log(checkProtocol.test('http://medium.com/')) // trueconsole.log(checkProtocol.test('//medium.com/')) // false13.请检查版本号是否正确
版本号必须采用 x.y.z 格式,其中 XYZ 至少为一位数字 。
// x.y.zconst versionRegexp = /^(?:d+.){2}d+$/console.log(versionRegexp.test('1.1.1'))console.log(versionRegexp.test('1.000.1'))console.log(versionRegexp.test('1.000.1.1'))14、获取网页上所有img标签的图片地址
const matchImgs = (sHtml) => {const imgUrlRegex = /<img[^>]+src=https://www.isolves.com/it/cxkf/sf/2023-09-05/"((?:https?:)?//[^"]+)"[^>]*?>/gilet matchImgUrls = []sHtml.replace(imgUrlRegex, (match, $1) => {$1 && matchImgUrls.push($1)})return matchImgUrls}console.log(matchImgs(document.body.innerHTML))15、按照3-4-4格式划分电话号码
let mobile = '13312345678' let mobileReg = /(?=(d{4})+$)/g console.log(mobile.replace(mobileReg, '-')) // 133-1234-5678最后
感谢你的阅读,期待您的关注和阅读更多优质文章 。
推荐阅读
- 微波炉可用的玻璃碗能在烤箱里用吗 微波玻璃碗可以放烤箱
- 贴瓷砖用的胶 贴瓷砖用的胶叫什么名字
- 九月钓鱼最好用的几种饵料,针对各种鱼情
- 正在用的20元纸币,是这特征价值21000元,你能找到吗?
- 橄榄油美容怎么使用的 橄榄油美容怎么使用
- 海藻保健
- Golang 中的 IO 包详解:常用的可导出函数详解
- 简单的实用的钓鱼方法 简单的实用的钓鱼方法大全
- 黄豆保健价值
- 被重用的秘诀:如何分清有效努力和无效付出?
