简体   繁体   中英

How to split a string in two by first digit occurrence?

Having a string like this

str = "word 12 otherword(s) 2000 19"

or like this

str = "word word 12 otherword(s) 2000 19"

I need to split the string in two, in order to have an array like this:

newstr[0] = first part of the string (ie "word" in the first case, "word word" in the second case);

newstr[1] = rest of the string (ie "12 otherword(s) 2000 19" in both cases).

I've tried to accomplish this using split and regex , without success:

str.split(/\d.*/) returns Array [ "word ", "" ] or Array [ "word word ", "" ]

while str.split(/^\D*/gm) returns Array [ "", "12 otherword(s) 2000 19" ]

Would you give me a suggestion? Even without using split and regex - if there's a better/faster (Vanilla JavaScript) solution.

There's 3 things going on here.

  1. String.split usually doesn't includes the matched delimiter in the return array. So splitting abc.split('b') would return ['a', 'c'] . This behavior can be changed by using a matching regex group; ie adding parens 'abc'.split(/(b)/) will return ['a', 'b', 'c'] .

  2. String.split will keep the delimter seperate from the other elements. Ie 'abc'.split(/(b)/) will return 3 elements ['a', 'b', 'c'] . Suffix the regex with .* to combine the last 2 elements: 'abc'.split(/(b.*)/) will return ['a', 'bc', ''] .

  3. Lastly, to ignore the last empty element, we send the 2nd param of 2 .

 let str = "word word 12 otherword(s) 2000 19"; let splitStr = str.split(/(\d.*)/, 2); console.log(splitStr);

You can match these parts:

 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]) }

See the regex demo .

Regex details :

  • ^ - start of a string
  • (\D*) - Group 1: any zero or more chars other than digits
  • (\d+[\w\W]*) - Group 2: one or more digits, and then any zero or more chars as many as possible.

Note you may .trim() the resulting parts when using them (print them with console.log([part1.trim(), part2.trim()]) ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM