本篇主要聊一聊关于项目中常用的JavaScript正则表达式.
去除HTML标签之间空字符
场景:之前碰到过一个问题,由于标签之间空格、换行符导致页面布局塌陷,用正则/ *[\r|\n] */gm去除即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const str = `<!DOCTYPE html> <html> <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" /> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <title>TEST</title> </head> <body> <div id="app"></div> </body> </html>` console.log(str.replace(/ *[\r|\n] */gm, ''));
|
去除HTML标签
场景:去除HTML标签,只获取标签里面的文本。
1 2 3
| const str = '<div style="color:skyblue;">Hellow</div><p></p>Word<span>!</span>'; const result = str.replace(/<[^>]+>/g,""); console.log(result);
|
去除HTML特定标签
场景:去除特定的HTML标签(包括标签属性、标签里面的内容)。
1 2 3
| const str = '<div style="color:skyblue;">Hellow</div><p></p>Word<span>!</span>'; const result = str.replace(/<(div)(([\s\S])*?)>.*<\/\1>/g, ''); console.log(result);
|
去除HTML标签属性
场景:去除特定的HTML标签属性、行内样式等。
1 2 3
| const str = '<div style="color:skyblue;">Hellow</div><p></p>Word<span>!</span>'; const result = str.replace(/(<[^\s\/>]+)\b[^>]*>/gi, "$1>") console.log(result);
|