1

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!

2
  • Which programming language are you using? Commented Aug 15, 2018 at 11:55
  • I am using Erlang but examples in JavaScript will be fine Commented Aug 15, 2018 at 11:56

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, it works in the example, what if we want to replace #test-id with something completely different, rhather than just prepending "section" before it?
@JonRiel Could you provide an example of "something completely different"? :)
sure! :) like "#content" Should result in #content .is-size-1-tablet {...}
@JonRiel I suppose then your replace() would look like s = s.replace(/(#test-id)(.+),/g, "#test-id$2,\n#content$2,")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.