Reputation: 63
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"
Upvotes: 2
Views: 176
Reputation: 1976
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\(.+?\)
.
Upvotes: 0
Reputation: 781058
Use a non-greedy regular expression:
style = style.replace(/translate3d\(.+?\)/,"asdf");
Putting ?
after +
makes it uses the shortest match instead of the longest.
Upvotes: 7
Reputation: 22905
.
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)'
Upvotes: 3