0

I wrote regular expression

/translateX\((?<X>-{0,1}\d+)px\)|translateY\((?<Y>-{0,1}\d+)px\)/g

For given string

translateX(381px) translateY(-94px)

To capture translateX and translateY values. Tested it by regex101.com service, it works well there. But, when I try it in JavaScript it capture translateX value which is 381 but not capture translateY which is -94. Do you have any ideas why is this happening?

regex101

https://i.sstatic.net/Nuj5X.png

JavaScript exec

console.log(/translateX\((?<X>-{0,1}\d+)px\)|translateY\((?<Y>-{0,1}\d+)px\)/g.exec("translateX(381px) translateY(-94px)"));

Using matchAll gives the same result.

JavaScript matchAll

console.log("translateX(381px) translateY(-94px)".matchAll(/translateX\((?<X>-{0,1}\d+)px\)|translateY\((?<Y>-{0,1}\d+)px\)/g).next().value.groups);

3
  • Consider adding the JS used into the question as a minimal reproducible example? Commented Jun 9, 2021 at 16:45
  • FYI, {0,1} is usually written as ? to indicate an optional pattern. Commented Jun 9, 2021 at 16:47
  • You're only calling .next() once in the last example, so you only get the first match. Try converting it to an array and you'll get all of the matches. Commented Jun 9, 2021 at 16:48

2 Answers 2

1

You're just calling .next() once, so you only get the first match. You need to loop over all the results of .matchAll().

for (m of "translateX(381px) translateY(-94px)".matchAll(/translateX\((?<X>-{0,1}\d+)px\)|translateY\((?<Y>-{0,1}\d+)px\)/g)) {
  console.log(m.groups);
}

You can also convert the iterator to an array.

console.log([..."translateX(381px) translateY(-94px)".matchAll(/translateX\((?<X>-{0,1}\d+)px\)|translateY\((?<Y>-{0,1}\d+)px\)/g)]
    .map(m => m.groups)) 

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

Comments

0

You can use this to find both values in one go:

/translateX\((?<X>-?\d+)px\).*translateY\((?<Y>-?\d+)px\)/g

console.log(/translateX\((?<X>-?\d+)px\).*translateY\((?<Y>-?\d+)px\)/g.exec("translateX(381px) translateY(-94px)"));

1 Comment

Yes, but I want to write expression that finds translateX and translateY regardless of their position. Like translateX(n) translateY(n) or translateY(n) translateX(n) - which is valid css transform values.

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.