Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left() function in Javascript or jQuery

Tags:

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

like image 556
Marcos Buarque Avatar asked Jan 29 '09 04:01

Marcos Buarque


People also ask

What is left in JavaScript?

Returns the leftmost characters of a string for the number of characters specified, or up to and excluding a substring.

Does JavaScript read left to right?

Both addition and subtraction operators have same precedence order, which means they are on the same level, and JavaScript will evaluate them from left to right.

How do you right a function in JavaScript?

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)

What is Substr in JavaScript?

The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.


2 Answers

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

like image 185
Sean Bright Avatar answered Oct 07 '22 13:10

Sean Bright


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.

like image 32
davidavr Avatar answered Oct 07 '22 13:10

davidavr