Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

正则表达式 #40

Open
ChelesteWang opened this issue Mar 6, 2022 · 0 comments
Open

正则表达式 #40

ChelesteWang opened this issue Mar 6, 2022 · 0 comments

Comments

@ChelesteWang
Copy link
Owner

创建一个正则表达式

  1. 字面量:const reg = /abc/i
  2. RegExp:const reg = new RegExp('abc', 'i')

与正则有关的几个方法

  1. 判断一个字符串是否满足正则:/abc/i.test('Abc')
  2. 找到字符串中匹配正则的所有地方:'AbcdaBc'.match(/abc/ig)
  3. 替换字符串中匹配到的地方:'AbcdaBc'.replace(/abc/ig, '***')
  4. 用正则去分割字符串:'AbcdaBc'.split(/abc/i)

工作中常用的几个正则

校验 URL 是否以 http:// 或者 https:// 开头

/^https?:\/\//

校验密码只包含数字和字母,且必须两者都包含,长度为 6 到 12 位

/^(?=.*[0-9])(?=.*[a-z])[0-9a-z]{6,12}$/i

把敏感词替换为 * 号

someString.replace(/(某主席|某主任|某某某)/g, m => '*'.repeat(m.length))

校验输入只能为数字,并且最多带两位小数

/^[0-9]+(\.[0-9]{0,2})?$/

其它正则的应用场景

驼峰、连字符相互转换

VS Code 有个插件 [change-case](https://marketplace.visualstudio.com/items?itemName=wmaurer.change-case) 可以实现字符的多种转换。我们拿其中一种举例,期望实现比如cardTitleExtracard-title-extra的互相转换。

解法如下:

// cardTitleExtra --> card-title-extra
someString.replace(/[A-Z]/g, m => `-${m.toLowerCase()}`)

// card-title-extra --> cardTitleExtra
someString.replace(/-(.)/g, (m, p) => p.toUpperCase())

markdown 语法解析

如何把 markdown 格式的字符串转换为对应的 html 字符串?

解法可以参考一些开源库的实现,比如[Marked](https://github.com/markedjs/marked/blob/master/lib/marked.js)。

写在最后

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant