JavaScript正则表达式
正则表达式可以被用于 RegExp 的 exec 和 test 方法以及 String 的 match、replace、search 和 split 方法。这些方法在 JavaScript 手册中有详细的解释。
使用正则表达式的方法(函数)
正则表达式标志
正则表达式基础
- 创建正则表达式对象(两种创建方式)
<script>
// 方法一
// 自变量
let reg = /\bis\b/g; //g表示全文匹配
let str = "He is a boy. This is a dog. Where is she?";
console.log(str.replace(reg, "IS"));
// 方法二
// 构造函数
let reg = new RegExp("\\bis\\b", "g");
let str = "He is a boy. This is a dog. Where is she?";
console.log(str.replace(reg, "IS"));
</script>
其输出都是:He IS a boy. This IS a dog. Where IS she?
2.(1)贪婪模式:
(2)非贪婪模式:
看一道例题
要求:利用正则表达式将字符串“一般圆周率为3.14,也可以为3,或者3.1415”中的数值提取到一个数组中。
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let n="一般圆周率为3.14,也可以为3,或者3.1415";
var s=n.match(/\d+(\.\d+)?/g);
console.log(s);
</script>
</body>
</html>