[英]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.