I just want a very handy way to extract the numbers out of a string in Javascript and I am thinking about using jQuery, but I prefer the method that proves to be the simplest. I have requested the "left" attribute of a css block using jQuery like this:
var stuff = $('#block').css("left")
The result of "stuff" is
1008px
I just want to get rid of the "px" because I need to do a parseInt of it. What is the best method? If Javascript had a left() function, this would be very simple. Thanks
To answer your other question, you can add a
left()
function to JavaScript's built-inString
prototype
class so all other strings will inherit it:And once you include this you can say:
I add helpers like
trim
andcapitalize
in a base JavaScript file for these kinds of things.$('#block').offset().left contains the actual left position value as an integer.
Just do a
parseInt("1008px", 10)
, it will ignore the 'px' for you.Left() is of almost no use here, as you'd first have to calculate the offset. You could, however, use a regular expression, to either pull out the number, or delete illegal characters:
That is, in case parseInt() isn't enough for you... :)
If you want to have that number without 'px' try it:
$('#block').position().left
That would be simplest on JQuery )