简体   繁体   中英

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"

Use a non-greedy regular expression:

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

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

. 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)'

it replaces untils the last ")" because the "+" quantifier is greedy by default. You can change this by placing a "?" just after it.

The correct regex is then: translate3d\\(.+?\\) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM