Having trouble getting numerical values from the computed transform matrix in Javascript? The result might be NaN

Recently, I've been working with the transform computed style property.

matrix3d(1.5, -7, 2, 0, 7, 1.5, 0, 0, -3, 1, 1, 0, 100, 0, 0, 1)

Now, my goal is to convert this into an array of numbers:

var s = window.getComputedStyle(element);
var mattrixArray = s.replace(/3d|matrix|(|)|\s|/g,'').split(','), l = mattrixArray.length;
for (var i=0; i<l; i++){
  mattrixArray[i] = parseInt(mattrixArray[i],10);
}
console.log(mattrixArray)

The result of this conversion is:

[NaN, -7, 2, 0, 7, 1.5, 0, 0, -3, 1, 1, 0, 100, 0, 0, 1]

However, when I omit parseInt(value), it displays correctly but as a string. How should I proceed?

Answer №1

Make sure to include the escape characters \( and \) in your regular expression.

/3d|matrix|\(|\)|\s|/g
           ^ ^

By fixing this issue, the regular expression will correctly exclude parentheses, resulting in an array that can be easily converted using parseInt or parseFloat:

["1.5", "-7", "2", "0", "7", "1.5", "0", "0", "-3", "1", "1", "0", "100", "0", "0", "1"]

Answer №2

Your regular expression isn't correctly replacing the parentheses. Make sure to add proper escaping!

var s = window.getComputedStyle(element);
var matrixArray = s.replace(/3d|matrix|\(|\)|\s|/g,'').split(',')
  , length = matrixArray.length;
for (var index=0; index<length; index++){
    matrixArray[index] = parseFloat(matrixArray[index],10);
}
console.log(matrixArray);

It's better to use parseFloat rather than parseInt for accurate values.

Another approach could be:

var matrixArray = s.split("(")[1].split(")")[0].split(',')

Update: After testing, splitting three times is approximately four times faster than utilizing a regular expression.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for fetching the value from checkbox buttons in Bootstrap 4?

I am currently utilizing Bootstrap's button plugin for my buttons, specifically with 6 checkbox buttons. I am in need of a method to extract the value of each checked button in order to perform some calculations. However, I am struggling to find a sol ...

In anticipation of a forthcoming .then() statement

Here is a return statement I have: return await foo1().then(() => foo2()); I am wondering, given that both foo1 and foo2 are asynchronous functions, if the code would wait for the resolution of foo2 or just foo1? Thank you. ...

What is the best way to deactivate ng-repeat using a button in AngularJS?

How can I disable the apply button once it has been clicked by the user in a list of stores based on services? I am using ng-repeat to display the listing. Additionally, how can I write an apply function to disable a particular service once it has been app ...

What is the method for accessing extra parameters in the signIn() callback function in [...nextauth]?

As per the Next Auth documentation, it is possible to pass extra parameters to the /authorize endpoint using the third argument of signIn(). The examples provided are: signIn("identity-server4", null, { prompt: "login" }) // always ask ...

Remove multiselect label in PrimeNG

I am attempting to change the multiselect label of selected items and replace it with a static default label. Here is what it currently shows: https://i.sstatic.net/qBNHG.png This is what I have tried: .p-multiselect-label { visibility: collapse; ...

Receiving the error message "TypeError: Page is not a valid constructor."

Having trouble with the "Page is not a constructor" error message, despite trying various solutions. Initially suspected an issue with JQuery, but upon inspection, everything appears to be in order. "TypeError: Page is not a constructor." admin_pages.js ...

Setting up Datatables using AngularJS

I am working on a controller that organizes song rankings based on sales data. Upon initialization, the controller automatically sends an HTTP GET request to retrieve all the songs needed for display (currently set at the top 20 songs). If I ever need to a ...

Ways to incorporate a unique debounce technique where the function is only executed every nth time

const _debounce = (num, fn) => { //implementation goes here } const originalFunction = () => { console.log('fired') } const _callFunc = () => _debounce(2, originalFunction) _callFunc() //The originalFunction does not run _callFun ...

Switch the Angular app written in Javascript to Typescript

I am looking to create a pluginable Angular app and came across this tutorial that uses RequireJs for loading scripts in the correct order. Now, I want to convert this project to TypeScript but I am unsure of how to incorporate RequireJs into TypeScript. ...

Transfer data as JSON from Flask to JavaScript

Having trouble sending data from Flask to JavaScript. I have the information from the database and added it to a dictionary. Now, I want to convert this data into a JSON object in JavaScript to display it on a map. Despite using JSON.parse in JavaScript, i ...

Maintain the current states when returning to a previous point in time

In my Angular app, I have multiple pages that allow users to make changes such as opening tabs and pills, modals, etc. For instance, if a user opens a modal and then clicks a link within that modal that takes them to another page, I want the original page ...

What is the best way to display all the videos that have been uploaded to YouTube?

I've been working with the Youtube API and PHP library, using this link: http://code.google.com/apis/youtube/2.0/developers_guide_php.html Currently, I'm making modifications to an existing app found at: The same functionality is also available ...

Creating a visual selection menu with icon options using jQuery or a similar framework

Currently, I am working on designing an HTML form that includes a field where users must select from a set of options such as sunny, cloudy, rainy, and more. I am seeking a creative alternative to using the <select> or <radio> input elements. ...

Nuxt router directing to incorrect URL upon refreshing the page

Let me show you exactly what I mean by setting up a demo Nuxt blog at https://example.com/nuxtblog/. This demonstration includes articles populated by the @nuxt/content package. The website has been generated statically using the nuxt generate command. Fol ...

Achieving the minimum width of a table column in Material-UI

Currently I am in the process of developing a React website with Material-UI. One query that has come up is whether it's feasible to adjust the column width of a table to perfectly fit the data, along with some extra padding on both ends? Outlined be ...

Transmitting information from the front-end Fetch to the back-end server

In my stack, I am using Nodejs, Express, MySQL, body-parser, and EJS. My goal is to trigger a PUT request that will update the counter by 1 when a button is pressed. The idea is to pass the ID of the clicked button to increment it by 1. app.put("/too ...

Data has been successfully acquired through the query, however, it cannot be accessed via the GraphQL API

After successfully building the API with Apollo Server and verifying its functionality in GraphiQL, I proceeded to make requests to the API from a front-end React app using Apollo Client. const [getUserPosts, { loading, error, data }] = useLazyQuery(GET_US ...

Ways to emphasize one button in a react native application?

Is there a way to emphasize one button among a group of buttons? I have a component that displays buttons. I have also imported a CustomButton that I created previously. const button = [ { title: '#Food', selected: false, ...

Exploring how to iterate through multiple arrays simultaneously in JavaScript

I have a specific problem with processing two sets of array objects to achieve a desired output. var parts={"Glenn": [12,22,32], "Ryan": [13,23,33], "Steve K": [14], "Jerom":[15,25,35], }; var labor={ "Glenn": [12,22,32], "Ryan": [13,23,33], "Steve K": [ ...

In WordPress, the magic_quotes feature is essential for json_decode to function properly

In my current project on the client side, I am dealing with an array of JavaScript objects. Upon submission, this array needs to be sent to PHP using a form and then further manipulated on the server-side. As I work on building or modifying the array of o ...