javascript 正则表达式,无法使 + 表达式起作用

标签 javascript regex

我正在尝试按照 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/

相关文章:

javascript - 具有意外结果的嵌套 z-index 分层

javascript - 如何获取当前加载的脚本名称和脚本的url变量?

javascript - JS/CSS : Preload images from the HTML file while they are hidden

Javascript 函数变量

正则表达式查找括号和文本

php - 从文本中删除 anchor

regex - 使用模式分割字符串

javascript - 在 React Router v4 中获取未定义的组件

Python:计算并替换同一次正则表达式?

ios - 在字符串 Swift 之间拆分 HTML 字符串