Left() function in Javascript or jQuery

2020-03-08 08:20发布

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

6条回答
神经病院院长
2楼-- · 2020-03-08 08:40

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.

查看更多
▲ chillily
3楼-- · 2020-03-08 08:40
parseInt(stuff);
查看更多
爷的心禁止访问
4楼-- · 2020-03-08 08:43

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

查看更多
甜甜的少女心
5楼-- · 2020-03-08 08:56

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

查看更多
一夜七次
6楼-- · 2020-03-08 08:57

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... :)

查看更多
▲ chillily
7楼-- · 2020-03-08 08:58

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

$('#block').position().left

That would be simplest on JQuery )

查看更多
登录 后发表回答