简体   繁体   中英

How do I split a string by numbers while keep the numbers in the first location of each substring?

Say I have a string like this:

1a2b3c4def

I want to split it into the following substrings, or an array:

  1. 1a
  2. 2b
  3. 3c
  4. 4debf

Every substring should start with a number character.

Another example:

Input: 1fw3fe.w6=3\657

Output:

  1. 1fw
  2. 3fe.w
  3. 6=
  4. 3\
  5. 6
  6. 5
  7. 7

If there is no number in the string, then do nothing.

What functions should I choose?

Update:

No more specific rules, just random input. I forgot to mention, the first character will ALWAYS be a digit. So if there are no more digits, put the whole string in an array.

Simple regex should do

const parts = '1fw3fe.w6=3\657'.match(/\d[^\d]*/g)

 const parts = String.raw`1fw3fe.w6=3\657`.match(/\d[^\d]*/g); console.log(parts);

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