<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script type="text/javascript">
/*
使用正则表达式的方法:
exec :一个在字符串中执行查找匹配的RegExp方法,它返回一个数组(未匹配到则返回 null)。
lastIndex :下一个匹配的索引值。
*/
const re = /lm/g;
const text = 'lmlmlmlmlm';
console.log(re.exec(text));//["lm", index: 0, input: "lmlmlmlmlm", groups: undefined]
console.log(re.lastIndex);//2
console.log(re.exec(text));//["lm", index: 2, input: "lmlmlmlmlm", groups: undefined]
console.log(re.lastIndex);//4
re.lastIndex = 0;
console.log(re.exec(text));//["lm", index: 0, input: "lmlmlmlmlm", groups: undefined]
//注意如果没有g全局匹配,Index是不会改变的
const re2 = /lm/;
const text2 = 'lmlmlmlmlm';
console.log(re2.exec(text2));//["lm", index: 0, input: "lmlmlmlmlm", groups: undefined]
console.log(re2.exec(text2));//["lm", index: 0, input: "lmlmlmlmlm", groups: undefined]
/*
练习:
匹配类似于aaaa 或者 bbbb 或者 cccc
匹配类似于aabb 或者 ccdd 或者 eeff
*/
const re3 = /(\w)\1\1\1/g;
const text3 = 'aaaabbbbcccc';
console.log(text3.match(re3));// ["aaaa", "bbbb", "cccc"]
const re4 = /(\w)\1(\w)\2/g;
const text4 = 'aabbccddeeff';
console.log(text4.match(re4));//["aabb", "ccdd", "eeff"]
</script>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script type="text/javascript">
/*
使用正则表达式的方法:
replace :一个在字符串中执行查找匹配的String方法,并且使用替换字符串替换掉匹配到的子字符串。
*/
const text = '012x741x';
console.log(text.replace('x', '谢'));//012谢741x
//精华部分来了(正则)
const re2 = /\wx/g;
const text2 = '012x741x';
console.log(text2.replace(re2, '谢'));//01谢74谢
/*
练习:
把类型xxyy形式变成yyxx
*/
const re3 = /(\w)\1(\w)\2/g;//说明一下:(\w)\1 匹配的字符复制一份 (\w)\2 匹配的字符复制一份,这个2代表着字符2(字符的位置),不是数量2
const text3 = 'xxyy';
console.log(text3.replace(re3, '$2$2$1$1'));
//另一种写法
const re4 = /(\w)\1(\w)\2/g;
let text4 = 'xxyy';
text4 = text4.replace(re4, function ($, $1, $2) {
console.log($);//xxyy
return `${$2}${$2}${$1}${$1}`
});
console.log(text4);//yyxx
</script>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script type="text/javascript">
/*
练习:
将类似于the-first-name,通过正则变成小驼峰theFirstName
*/
const re = /-(\w)/g;
let text = 'the-first-name';
text = text.replace(re, function ($, $1) {
return $1.toUpperCase();
});
console.log(text);
</script>
</html>