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
Returns the leftmost characters of a string for the number of characters specified, or up to and excluding a substring.
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.
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, ...)
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.
Just do a parseInt("1008px", 10)
, it will ignore the 'px' for you.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With