我的目标:
我正在尝试解析 css 字符串以检索不同的部分,例如 css 规则、导入、注释...
我做了什么:
我的函数首先检索注释,然后检索导入,最后检索规则 block 。
一旦检索到这些部分,每个部分都会记录到控制台。
我的问题:
我的问题是,当我测试它时,当规则 block 部分记录到控制台时,我的代码似乎会生成随机数。
我的代码:
function output(css) {
if(typeof css === 'string') {
var current = css;
// remove comments
var comments = [];
current = current.replace(/\s*\/\*[^*]*\*+([^/*][^*]*\*+)*\/|^\/\/[^\n]*\n?/gim, c=>comments.push(c.trim()));
// retrieve @ imports
var imports = [];
current = current.replace(/@[^;{]+;/gi, imp => imports.push(imp.trim()));
// retrieve rules blocks
var rulesBlocks = [];
current = current.replace(/[^};]+{[^{]*}/gi, block => {
rulesBlocks.push(block.trim());
});
console.log(comments, imports, rulesBlocks);
}
}
var css = document.getElementById('css').innerText;
output(css);
<pre id="css"><code>
#id, .class {
#id {
}
}
/**
*/
@import url('http://www.test.com/test.min.js/');
/*
@import url('http://www.test.com/test.min.js/');
*/
/***/
//#id, .class {
#id, .class {
#id {
& {
}
}
}
#id, .class {
#id {
}
}
declaration {
data: test;
}
declaration2 declaration {
data
}
@font-face {
font-family: myFirstFont;
src: url(sansation_light.woff);
}
@font-face {
font-family: myFirstFont;
src: url(sansation_light.woff);
}
</code></pre>
正如您所看到的,如果运行它,控制台会在这一行中显示随机数:
“1\n123\n4#id,.class {\n\t#id {\n\t\t& {\n\t\t}\n\t}\n}”
为什么它会生成随机数?为什么控制台显示1、123和4?
最佳答案
因为数组push返回数组的新长度,并且您将该返回值用作 replacement .
You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string.
所以:
current = current.replace(/@[^;{]+;/gi, imp => imports.push(imp.trim()));
将用imports
的新长度替换表达式的每个实例。
如果你想避免这个问题,你可以使用 Washington Guedes 的建议,在推送后的注释中添加 &&'';
,或者直接 return imp
(等)在替换函数中,或者重写该函数以使用更惯用的 exec
方法。
关于Javascript正则表达式替换-出现随机数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44636197/