Regular Expression (Regex) on CSS3 Transform String

1.4k views Asked by At

Given a string "translateX(-50%) scale(1.2)" with N transform functions

1) How can I match the names ["translateX", "scale"]?

2) How can I match the values ["-50%", "1.2"]?

2

There are 2 answers

3
hwnd On BEST ANSWER

If you absolutely must use regular expression to do this, you can use the exec() method in a loop, pushing the match result of the captured group(s) to the desired arrays of choice.

var str = 'translateX(-50%) scale(1.2)'
var re  = /(\w+)\(([^)]*)\)/g, 
names = [], vals = [];

while (m = re.exec(str)) {
  names.push(m[1]), vals.push(m[2]);
}

console.log(names) //=> [ 'translateX', 'scale' ] 
console.log(vals)  //=> [ '-50%', '1.2' ]

The regular expression uses two capture groups, the first matches/captures word characters only, the second uses negation which will match any character except ) "zero or more" times.

6
Oriol On

Try something like (\w+)\((.+?)\):

  • (\w+): Match the regular expression below and capture its match into backreference number 1
    • \w+: Match a single character that is a “word character” (letters, digits, and underscores)
      • +: Between one and unlimited times, as many times as possible, giving back as needed (greedy)
  • \(: Match the character “(” literally
  • (.+?): Match the regular expression below and capture its match into backreference number 2
    • .+?: Match any single character that is not a line break character
      • +?: Between one and unlimited times, as few times as possible, expanding as needed (lazy)
  • \): Match the character “)” literally
var str = "translateX(-50%) scale(1.2)",
    regex = /(\w+)\((.+?)\)/g,
    match, names = [], values = [];
while(match = regex.exec(str)) {
    names.push(match[1]);
    values.push(match[2]);
}