Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trim "px" off the end of Jquery var

Tags:

jquery

trim

I have a variable which stores the css value of a margin. I want to remove the "px" from the end so that i just have the number to work with. How can i do this?

like image 952
phil crowe Avatar asked Sep 02 '10 08:09

phil crowe


2 Answers

var x = "1px"; var y = parseInt(x, 10); // specify radix to prevent unpredictable behavior 
like image 195
Alex Reitbort Avatar answered Sep 23 '22 09:09

Alex Reitbort


Option 1:

parseInt('200px', 10); 

The parseInt() function parses a string and returns an integer. Don't change the 10 found in the above function (known as a "radix") unless you know what you are doing.

Output will be: 200.

Option 2 (I personally prefer this option)

parseFloat('200px') 

Output will be: 200

The parseFloat() function parses a string and returns a floating point number.

The parseFloat() function determines if the first character in the specified string is a number. If it is, it parses the string until it reaches the end of the number, and returns the number as a number, not as a string.

The advantage of Option 2 is that if you use decimal numbers (e.g. 200.32322px) you will get the number returned with the values behind the decimal point. Useful if you need specific numbers returned.

like image 40
Arman Nisch Avatar answered Sep 26 '22 09:09

Arman Nisch