views:

10133

answers:

6

Hi, 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

+8  A: 

Just do a parseInt("1008px", 10), it will ignore the 'px' for you.

Sean Bright
parseInt(stuff,10); //Don't forget the radix
some
+3  A: 
parseInt(stuff);
John Boker
parseInt(stuff,10); //Don't forget the radix
some
+2  A: 

To answer your other question, you can add a left() funtion to JavaScript's built-in String prototype class so all other strings will inherit it:

String.prototype.left = function(n) {
    return this.substring(0, n);
}

And once you include this you can say:

var num = "1008px".left(4);

I add helpers like trim and capitalize in a base JavaScript file for these kinds of things.

davidavr
fwiw, the native substr() is equivalent to left(), but I'm all for adding cheap flexibility
annakata
@annakata: substr() has not been standardized by ECMAScript and is thus deprecated. And still, you'd need to specify the start and length, but you are right, left() is just a convenience.
davidavr
There also is slice (15.5.4.13)
some
+1  A: 

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:

var value = "1080px";
var num = value.replace(/[^\d]+/g, '');
// or
var num = value.replace(/\D+/g, '');
// or
var num = value.match(/\d+/)[0];

That is, in case parseInt() isn't enough for you... :)

bart
+6  A: 

$('#block').offset().left contains the actual left position value as an integer.

svinto
A: 

Hi,

I need to get left, but in firefox 3.5, I just got "auto".

console.log($("#menu_").css("left")); auto

The element have float: left and contained inside other div. I try to get the parent left, but it return "aotu" too.

I'm using jquery 1.2.6. Is this have been fixed in jquery 1.3.1?

Donny Kurnia