[Solved] Left() function in Javascript or jQuery

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


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

Solution #1:

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

Respondent: Sean Bright

Solution #2:

To answer your other question, you can add a left() function 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.

Respondent: davidavr

Solution #3:

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

Respondent: svinto

Solution #4:

Respondent: John Boker

Solution #5:

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… 🙂

Respondent: bart

Solution #6:

If you want to have that number without ‘px’ try it:


That would be simplest on JQuery )

Respondent: sol0mka

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy