I need a simple way to extract numbers from a string in JavaScript. I’m using jQuery to get the left
attribute of a CSS block like this:
var stuff = $('#block').css("left");
The result is something like "1008px"
, but I need just the number so I can use parseInt
. If java script left
had a built-in function like left()
, this would be straightforward. What’s the best way to achieve this?
You can use parseInt():
var leftValue = parseInt($('#block').css("left"));
It automatically removes “px” and extracts the number.
Also, try using .replace() with a Regex:
var leftValue = $('#block').css("left").replace("px", "") * 1;
It removes “px” and converts the string to a number.
You can use match() with a regex (more flexible):
var leftValue = parseFloat($('#block').css("left").match(/\d+/)[0]);
It works even if px is missing or mixed with other text.