【代码】JS通过正则表达式替换字符串

前言

JS通过正则表达式替换字符串

源代码

  • <>"&替换成实体字符
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let str = "";

(function(str){
return str.replace(/<|>|"|&/g, function(match) {
switch (match) {
case "<":
return "&lt;";
case ">":
return "&gt;";
case "\"":
return "&quot;";
case "&":
return "&amp;";
}
});
})(str);

完成

参考文献

哔哩哔哩——黑马程序员