我有一个包含CSS代码的JavaScript字符串。
使用此字符串我想获得2个循环和没有正则表达式
第一件事:选择器/ s
第二件事:获得的选择器的属性
我的理念:
var myResult = [], myString = /* CSS content */;
while(myString.length > 0)
{
var
mySelector = /* Obtain the first selector occurrence. */,
myRules = /* Obtain the rules of the founded selector */;
myResult.push(mySelector, myRules);
myString = myString.replace(mySelector, null);
myString = myString.replace(myRules, null);
// then now loop and find the next first selector and his rules.
}
示例:
var myResult = [], myString = "main { color: #405050; margin: 0; } hr, progress { width: 100%; }";
while(myString.length > 0)
{
var
mySelector = /* Obtain the first selector occurrence */,
myRules = /* Obtain the rules of the founded selector */;
myResult.push(mySelector, myRules);
myString = myString.replace(mySelector, null);
myString = myString.replace(myRules, null);
// then now loop and find the next first selector and his rules.
}
// now myResult must contain: "main", "color: red; margin: 0;", "hr, progress", "width: 100%"
有人可以帮助我在不使用正则表达式的情况下执行此算法吗?
答案 0 :(得分:0)
这适用于你
var myString = "main { color: #405050; margin: 0; }";
var selector = "";
var myResult = [];
for (var i = 0; i < myString.Length; i++)
{
if ((myString[i] >= 65 && myString[i] <= 90) || (myString[i] >= 97 && myString[i] <= 122) || myString[i] == '.' || myString[i] == '#')
/* keep going if you find any thing that is . or # of alphabets */
{
selector += myString[i];
}
else
{
for (var j = i + 1; j < myString.Length; j++)
{
if ((myString[j] >= 65 && myString[j] <= 90) || (myString[j] >= 97 && myString[j] <= 122)) // rule start
/* keep going unless the rule ends */
{
var currRule = "";
for (var l = j; l < myString.Length; l++)
{
currRule += myString[l];
if (myString[l] == ';')
{
j = l;
i = l;
break;
}
}
myResult.push(mySelector, myRules);
}
}
}
}