使用java脚本或正则表达式从值中分割数字和字符串
Split number and string from the value using java script or regex
我有一个值"4.66lb"
和我想分开"4.66"answers"lb"使用正则表达式。
我尝试了下面的代码,但它只分隔数字"4,66"!!但是我想要的值是4.66和lb。
var text = "4.66lb";
var regex = /('d+)/g;
alert(text.match(/('d+)/g));
试一试:
var res = text.match(/('d+(?:'.'d+)?)('D+)/);
res[1]
包含4.66
res[2]
含lb
为了匹配4/5lb
,你可以使用:
var res = text.match(/('d+(?:[.'/]'d+)?)('D+)/);
你也可以使用字符类,
> var res = text.match(/([0-9'.]+)('w+)/);
undefined
> res[1]
'4.66'
> res[2]
'lb'
让我用一个例子来解释
var str = ' 1 ab 2 bc 4 dd'; //sample string
str.split(/'s+'d+'s+/)
result_1 = ["", "ab", "bc", "dd"] //regex not enclosed in parenthesis () will split string on the basis of match expression
str.split(/('s+'d+'s+)/) //regex enclosed in parenthesis () along with above results, it also finds all matching strings
result_2 = ["", " 1 ", "ab", " 2 ", "bc", " 4 ", "dd"]
//here we received two type of results: result_1 (split of string based on regex) and those matching the regex itself
//Yours case is the second one
//enclose the desired regex in parenthesis
solution : str.split(/('d+'.*'d+[^'D])/)
相关文章:
- 通过单击表单中的按钮,在代码生成中使用javascript生成字母数字代码
- 测试索引值是否等于某个数字的倍数
- 将数字转换为一定数量的硬币
- 键入最后一位数字后自动提交
- 如何在javascript中迭代数字列表
- Javascript逻辑运算符和字符串/数字
- regex分割在Javascript中不起作用的数字和非数字组
- 可以使用正则表达式分割数字
- 用十进制分割字符串和数字的正则表达式
- 按十进制分割数字并返回2个单独的元素
- 子字符串,分割,字符串到数字和RGB到HEX
- 从字符串分割数字的正则表达式
- 同时确保数字不能再被分割
- JavaScript -数字多分割
- 使用java脚本或正则表达式从值中分割数字和字符串
- 分割文本基于第一个数字javascript
- 在小数点或字符串末尾使用regex分割数字
- 用正则表达式在数字和字符串之间进行Javascript分割
- 分割出现数字的地方
- 通过逗号将字符串分割成数字,然后打印,最终会跳过1个y值