1

I have some data in a string, for example

const rawData = `1   Jon Doe 3434 535 3 3 353 HI 3535
2    Jane Smith 23 5235 5 5 2352 HELLO 3543
3      Some Guy 4534 35 5345 4 5345 MEOW 4354`

I want to use the .split() method to make each line (starting with the order number to the end of the last value) its own value in an array.

I have tried

rawData.split(/([0-9]+\s+[A-Z][a-z])/g);

the regex finds a number followed by some whitespace then a capital letter and a lower cased letter (the order number until the start of the first name)

this returns

["", "1 Jo", "n Doe 3434 535 3 3 353 HI 3535", "2 Ja", "ne Smith 23 5235 5 5 2352 HELLO 3543", "3 So", "me Guy 4534 35 5345 4 5345 MEOW 4354"]

I would like to have 3 values by splitting the string at the start of the regex. So I would like to end up with:

["1 Jon Doe 3434 535 3 3 353 HI 3535", "2 Jane Smith 23 5235 5 5 2352 HELLO 3543", "3 Some Guy 4534 35 5345 4 5345 MEOW 4354"]

I can think a workaround, using a for loop to join the values in the array after. I'm curious if there is a way to do it on one line. Thanks!

EDIT

I just found out about lookahead in regex, this works:

rawData.split(/\s(?=\d+\s+[A-Z][a-z])/g);
3
  • I think you mean "at the start of a string returned by a regex", not at the start of the regex itself. Commented Jan 28, 2020 at 19:13
  • @isherwood yup thats what I mean, still new to using regex so thanks for clarifying Commented Jan 28, 2020 at 20:23
  • @UthistranSelvaraj that worked, thanks! although I found a way to do it if they weren't on new lines, added to the original question Commented Jan 28, 2020 at 20:24

1 Answer 1

2

Why not split by new line?

const rawData = `1   Jon Doe 3434 535 3 3 353 HI 3535
2    Jane Smith 23 5235 5 5 2352 HELLO 3543
3      Some Guy 4534 35 5345 4 5345 MEOW 4354`,
    result = rawData.split(/\n/);

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.