[英]How to split a string in two by first digit occurrence?
有这样的字符串
str = "word 12 otherword(s) 2000 19"
或者像这样
str = "word word 12 otherword(s) 2000 19"
我需要将字符串分成两部分,以便拥有这样的数组:
newstr[0] = first part of the string
(即第一种情况下的“word”,第二种情况下的“word word”);
newstr[1] = rest of the string
(即“12 otherword(s) 2000 19”在这两种情况下)。
我尝试使用split
和regex
来完成此操作,但没有成功:
str.split(/\d.*/)
返回Array [ "word ", "" ]
或Array [ "word word ", "" ]
而str.split(/^\D*/gm)
返回Array [ "", "12 otherword(s) 2000 19" ]
你能给我一个建议吗? 即使不使用split
和regex
- 如果有更好/更快的(Vanilla JavaScript)解决方案。
这里发生了 3 件事。
String.split 通常在返回数组中不包含匹配的分隔符。 所以拆分abc.split('b')
会返回['a', 'c']
。 可以通过使用匹配的正则表达式组来更改此行为; 即添加括号'abc'.split(/(b)/)
将返回['a', 'b', 'c']
。
String.split 将使分隔符与其他元素分开。 即'abc'.split(/(b)/)
将返回 3 个元素['a', 'b', 'c']
。 使用.*
为正则表达式添加后缀以组合最后两个元素: 'abc'.split(/(b.*)/)
将返回['a', 'bc', '']
。
最后,为了忽略最后一个空元素,我们发送2
的第二个参数。
let str = "word word 12 otherword(s) 2000 19"; let splitStr = str.split(/(\d.*)/, 2); console.log(splitStr);
您可以匹配这些部分:
const strs = ["word 12 otherword(s) 2000 19", "word word 12 otherword(s) 2000 19"]; for (var s of strs) { const [_, part1, part2] = s.match(/^(\D*)(\d+[\w\W]*)/) console.log([part1, part2]) }
请参阅正则表达式演示。
正则表达式详细信息:
^
- 字符串的开头(\D*)
- 第 1 组:除数字以外的任何零个或多个字符(\d+[\w\W]*)
- 第 2 组:一个或多个数字,然后是尽可能多的零个或多个字符。 请注意,您可以.trim()
使用它们时生成的部分(使用console.log([part1.trim(), part2.trim()])
打印它们)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.