练习题
1.把get-element-by-id转为驼峰命名
var str = 'get-element-by-id'
const reg = /-\w/g
const newStr = str.replace(reg, word => {
console.log(word, 'word12')
return word.substring(1).toUpperCase()
})
console.log(newStr, 'newStr')
// getElementById
2.判断电话号码
function isPhone(tel) {
var regx = /^1[34578]\d{9}$/;
return regx.test(tel);
}
3.查找重复单词
var str = "Is is the cost of of gasoline going up up";
var patt1 = /\b([a-z]+) \1\b/ig;
document.write(str.match(patt1));
\1 指定第一个子匹配项 back reference 反向参考~~~~
4.abcdebbcde匹配叠词(考察反向引用)
https://www.cnblogs.com/guorange/p/6693168.html
源字符串:abcdebbcde
正则表达式:([ab])1
对于正则表达式“([ab])1”,捕获组中的子表达式“[ab]”虽然可以匹
配“a”或者“b”,但是捕获组一旦匹配成功,反向引用的内容也就确定了。如
果捕获组匹配到“a”,那么反向引用也就只能匹配“a”,同理,如果捕获组匹
配到的是“b”,那么反向引用也就只能匹配“b”。由于后面反向引用“1”的限
制,要求必须是两个相同的字符,在这里也就是“aa”或者“bb”才能匹配成
功。~~~~
5.给定字符串str,检查其是否符合如下格式
XXX-XXX-XXXX 其中X为Number类型
function matchesPattern(str) {
return /^(\d{3}-){2}\d{4}$/.test(str);
6、JS实现千位分隔符
前端没有后顾,所以只讲解前瞻
首先我们要理解正则的解析顺序 正则解析顺序->从左向右,向右边看就是前瞻
?=
正向前瞻 例如: /b(?=a)/.test('bab') 看前瞻的部分是否是a //true
?!
负向前瞻 /b(?!a)/.test('bb') 看前瞻部分是不是非a //true
const number = 123456789123
var regx = /\d{1,3}(?=(\d{3})+$)/g
// document.write((number + '').replace(regx, '$&,'))
// $&表示与regx相匹配的字符串123 456 789 最后的123
// 没有被匹配上是因为?= 前瞻的时候没有3位数~~~~字
document.write(
(number + '').replace(regx, function (world) {
//这里的world就是上面的$& 即 123 456 789
return world + ','
}),
) ~~~~
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。