超级字符串内class正则匹配替换 可以用于css modules
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>超级字符串内class正则匹配替换</title>
<style type="text/css">
</style>
</head>
<body>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script type="text/javascript">
let text = 'hello world!';
let tpl =
`<div id="m-toast" class="m-toast m-toast-new"}>
<div class="m-toast-inner"}>
<div class="m-toast-text"}>
${text}
</div>
</div>
</div>
<div></div>`;
let styles = {
"m-toast": 1,
"m-toast-new": '1-1',
"m-toast-inner": 2,
"m-toast-text":3
}
function buildTpl(tpl) {
let reg = /class=\".*?\"/g;
result = tpl.match(reg);
for (let i = 0; i < result.length; i++) {
let tempReg = /\".*?\"/g;
let tempResult = result[i].match(tempReg)[0];
tempResult = tempResult.slice(1, tempResult.length - 1);
tempResult = tempResult.split(/\s+/);
let myStyle = '';
for (let j = 0; j < tempResult.length; j++) {
if (typeof styles[tempResult[j]] !== 'undefined') {
myStyle += styles[tempResult[j]] + ' ';
}
}
let r = result[i].replace(tempReg, '"' + myStyle + '"');
tpl = tpl.replace(result[i], r);
}
return tpl;
}
tpl = buildTpl(tpl);
console.log(tpl);
</script>
</body>
</html>