Reputation: 513
Let's say I have a css transform property that looks like this:
scale(1.02, 2.0) rotateX(50) rotateY(20) rotateZ(10) skew(100deg)
I need to remove the substring rotateX(50) rotateY(20) rotateZ(10)
from the property AND get the 3 values 50
, 20
, and 10
as an array
How would you do this using javascript?
Upvotes: 1
Views: 1107
Reputation: 12422
I'd use 3 separate RegExp so it will work no matter the order of the rotate
statements. This example uses ES6 destructuring
for brevity but you could easily write it in ES5 using a temporary variable to
hold the .match
results.
var transformString = 'scale(1.02, 2.0) rotateX(50) rotateY(20) rotateZ(10) skew(100deg)';
// The first variable receives the entire match which we will later remove from
// transformString. The second variable receives the match group, the numeric
// value inside the parentheses
var [xText, xValue] = transformString.match(/\srotateX\((\d+)\)/i);
var [yText, yValue] = transformString.match(/\srotateY\((\d+)\)/i);
var [zText, zValue] = transformString.match(/\srotateZ\((\d+)\)/i);
// remove rotate commands
[xText, yText, zText].forEach(function (text) {
transformString = transformString.replace(text, '');
});
var values = [xValue, yValue, zValue];
console.log(transformString, values);
Note that the numbers we captured are string representations of those numbers, not actual numbers. If you need them to be numbers you could use .map
to convert them to numbers.
values = values.map(function (n) {
return +n;
});
Upvotes: 1
Reputation:
Try this script:
var txt = 'scale(1.02, 2.0) rotateX(50) rotateY(20) rotateZ(10) skew(100deg)';
var array = txt.match(/\(\d+(?=\))/g).map(function(x){return x.slice(1)});
document.write(array);
var new_text = txt.replace(/\).* /, ') ');
document.write('<br>' + new_text);
Hope it helps.
Upvotes: 1
Reputation: 2872
Use this regex rotateX\((\d+)\)\s+rotateY\((\d+)\)\s+rotateZ\((\d+)\)
;
var transform = 'scale(1.02, 2.0) rotateX(50) rotateY(20) rotateZ(10) skew(100deg)';
var match = transform.match(/rotateX\((\d+)\)\s+rotateY\((\d+)\)\s+rotateZ\((\d+)\)/);
var arr = match.slice(1, 4);
Upvotes: 1