Jon Riel
Jon Riel

Reputation: 409

Regex - duplicate CSS selectors and replace with new selector

In an effort to limit the scope of css libraries used by different parties in a larger project(and thereby reducing conflicts) I have been successful in creating a regex code that prepends all css selectors with a given selector (in this case #test-id, example here: https://regex101.com/r/SNJZx2/1).

To make this endeavour more useful, I want to

  1. duplicate all prefixed selectors (selectors having a preceeding #test-id and end with a , or {)
  2. replace the duplicate value of #test-id with another selector (let's say section#test-id-1)

Example CSS:

#test-id .breadcrumb,
#test-id .button {
  user-select: none;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif
}

@media screen and (min-width:769px), print {
  #test-id .is-size-1-tablet {
    font-size: 3rem !important
  }
}

Desired result:

section#test-id-1 .breadcrumb, 
#test-id .breadcrumb,
section#test-id-1 .button, 
#test-id .button {
  user-select: none;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif
}

@media screen and (min-width:769px), print {
  section#test-id-1 .is-size-1-tablet,
  #test-id .is-size-1-tablet {
    font-size: 3rem !important
  }
}

Note: Real-world files may be minified, meaning that matching for newline ^ as a solid starting point, may not work.


So that we now have successfully limited the scope of CSS files, and also allow it to be applied to multiple "sections".

What are some RegEx approaches that would be helpful here?

Cheers!

Upvotes: 1

Views: 145

Answers (1)

Ildar Akhmetov
Ildar Akhmetov

Reputation: 1431

This should work:

s = s.replace(/(#test-id.+),/g, "$1,\nsection$1,")
s = s.replace(/(#test-id.+){/g, "$1,\nsection$1{")

We need two regular expressions here for the two options: 1. If the definition is not the last one (i.e., ends with a comma) 2. If it is the last one (ends with a curly brace).

Here is a fiddle: https://jsfiddle.net/vs0mrcfa/9/

Upvotes: 1

Related Questions