forked from tomfanxiaojun/Front-End-Interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
regexp.html
113 lines (106 loc) · 3.52 KB
/
regexp.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<!DOCTYPE html>
<html>
<head>
<title>RegExp Demo</title>
<style>
section {
display: flex;
flex-direction: column;
justify-content: space-around;
height: 300px;
padding: 0 200px;
}
section * {
min-height: 30px;
}
#err {
color: red;
}
#result {
line-height: 30px;
}
.info {
background: #00c5ff;
padding: 2px;
margin: 2px;
display: inline-block;
}
</style>
</head>
<body>
<section>
<div id="err"></div>
<input id="regex" placeholder="请输入正则表达式">
<input id="text" placeholder="请输入测试文本">
<button id="run">测试一下</button>
<div id="result"></div>
</section>
<script>
(function() { // 获取相应dom元素
var regexInput = document.getElementById("regex");
var textInput = document.getElementById("text");
var runBtn = document.getElementById("run");
var errBox = document.getElementById("err");
var resultBox = document.getElementById("result"); // 绑定点击事件
runBtn.onclick = function() { // 清除错误和结果
errBox.innerHTML = "";
resultBox.innerHTML = ""; // 获取正则和文本
var text = textInput.value;
var regex = regexInput.value;
if (regex == "") {
errBox.innerHTML = "请输入正则表达式";
} else if (text == "") {
errBox.innerHTML = "请输入测试文本";
} else {
regex = createRegex(regex);
if (!regex) return;
var result, results = []; // 没有修饰符g的话,会死循环
if (regex.global) {
while (result = regex.exec(text)) {
results.push(result);
}
} else {
results.push(regex.exec(text));
}
if (results[0] == null) {
resultBox.innerHTML = "匹配到0个结果";
return;
} // 倒序是有必要的
for (var i = results.length - 1; i >= 0; i--) {
var result = results[i];
var match = result[0];
var prefix = text.substr(0, result.index);
var suffix = text.substr(result.index + match.length);
text = prefix + '<span class="info">' + match + '</span>' + suffix;
}
resultBox.innerHTML = "匹配到" + results.length + "个结果:<br>" + text;
}
}; // 生成正则表达式,核心函数
function createRegex(regex) {
try {
if (regex[0] == "/") {
regex = regex.split("/");
regex.shift();
var flags = regex.pop();
regex = regex.join("/");
regex = new RegExp(regex, flags);
} else {
regex = new RegExp(regex, "g");
}
return regex;
} catch (e) {
errBox.innerHTML = "无效的正则表达式";
return false;
}
}
})();
</script>
</body>
</html>