Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't match this regular expression in Javascript

I need to apply a regexp for replacing a block of a string.

this is my code:

var style = "translate(-50%, -50%) translate3d(3590px, 490px, 0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) scale(1)";

style = style.replace(/translate3d\(.+\)/,"asdf");

I need to replace that part: "translate3d(3590px, 490px, 0px)" but it doesn't work because it replaces until the last ")" so it will be: "translate(-50%, -50%) asdf"

like image 383
asdfasf asdfasd Avatar asked Jul 26 '26 23:07

asdfasf asdfasd


2 Answers

Use a non-greedy regular expression:

style = style.replace(/translate3d\(.+?\)/,"asdf");

Putting ? after + makes it uses the shortest match instead of the longest.

like image 83
Barmar Avatar answered Jul 28 '26 11:07

Barmar


. matches all characters. Force it to skip the closing parentheses:

style = style.replace(/translate3d\([^)]+\)/,"asdf");

Trying it out:

> var style = "translate(-50%, -50%) translate3d(3590px, 490px, 0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) scale(1)";
> style = style.replace(/translate3d\([^)]+\)/,"asdf");
'translate(-50%, -50%) asdf rotateX(0deg) rotateY(0deg) rotateZ(0deg) scale(1)'
like image 38
SheetJS Avatar answered Jul 28 '26 13:07

SheetJS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!