我正在尝试按照 CSS 格式从字符串中提取数字,如下所示:
str == "50.1px"
sz = str.match(/+([0-9]|\.)/)
除非我转义它,否则它会提示 +
表达式,但随后 sz
为空。如果我删除 +
它只返回第一个数字。我完全被难住了。
最佳答案
为此,您应该只使用 Javascripts .parseFloat()
。它会自动去除尾随字符。
sz = parseFloat('50.1px'); // 50.1
MDN:
parseFloat parses its argument, a string, and returns a floating point number. If it encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all succeeding characters. Leading and trailing spaces are allowed.
关于javascript 正则表达式,无法使 + 表达式起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11727114/