Claudiu Creanga
Claudiu Creanga

Reputation: 8366

Regex to transform all rem-calc in pixels

I have to port some sass to css and I have thousands of rem-calc declarations.

So I need for example rem-calc(10 15 20 15); to be 10px 15px 20px 15px;

Started with /rem-calc\([1-9]/ but don't know how to approach it. If some of the regex experts could help

Test case samples:

  padding: rem-calc(10 15 20 15);
  width: rem-calc(415);

Should become:

padding: 10px 15px 20px 15px;
width: 415px;

Thanks!

Upvotes: 2

Views: 620

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627264

Just a rough idea: if you match these rem-calc strings with /rem-calc\((.*)\);/ regex and then grab Group 1 value to split with spaces and add px, then it willl look like

var re = /rem-calc\((.*)\);/g;
var str = 'rem-calc(10 15 20 15);';
var m = str.match(re);
if (m) {
  console.log(m[1].split(/\s*(\d+)\s*/).filter(Boolean).join("px ") + "px");
}

The /\s*(\d+)\s*/ splits with digits enclosed with whitespaces, then .filter(Boolean) removes empty values and join("px ") adds px after the digits. Then, we need to append px at the end.

Upvotes: 2

Related Questions