Steve B Steve B - 4 months ago 6
Javascript Question

Trying to clean up wrong CSS rules using js code

I have bad css files with rules like this (I can't control the generation of these files):

.class html {
}

.class2 html,.class3 html {

}

html {

}

html .class4 {

}

.class body {
}

.class2 body,.class3 body {
}

body {
}

body .class4 {
}


as you can see, some HTML and BODY rules are put after class name.

What I want to do is to reverse this rules to obtain proper qualifier (tag then class).

My expected result is:

html .class {
}

html .class2 ,html .class3 {

}

html {

}

html .class4 {

}

body .class {
}

body .class2 ,body .class3 {

}

body {

}

body .class4 {

}


I tried using a regex :
([^,]+\s+)(html|body)
with this substitution :
$2 $1
, but I don't get what I want. (Repro on regex101)

How to reach my goal ?

PS: this will ends in a custom gulp task, so a js regex solution is required.

Answer

You can use

(\.\S+)(\s+)(html|body)

and replace with $3$2$1.

The regex demo is here.

Expression details:

  • (\.\S+) - a literal dot followed with one or more non-whitespaces (Group 1)
  • (\s+) - one or more whitespaces (Group 2)
  • (html|body) - either html or body literal character sequences (Group 3).

The replacement pattern contains the group backreferences that follow in the opposite direction for swapping to occur.

To account for cases like .class .classN html, use

/(\.\S+(?:\s+\.\S+)*)(\s+)(html|body)/g

where a noncapturing group (?:\s+\.\S+)* is quantified with * ((zero or more times).

Comments