-1

I would like to split the following string at each letter using String.prototype.split(/[a-zA-Z]/):

'M 10 10L 150 300'

The result:

[ "", " 10 10", " 150 300" ]

But I want to receive this:

[ "", "M 10 10", "L 150 300" ]


What is the fastest way to get that result using JavaScript?

1
  • 1
    This comes close: input.split(/(?=[A-Za-z])/) Commented Jan 4, 2018 at 1:39

1 Answer 1

1

Try use match with /[a-zA-Z][^a-zA-Z]*/g to capture a letter and the following non letter characters:

let s = 'M 10 10L 150 300'

console.log(
  s.match(/^[^a-zA-Z]+|[a-zA-Z][^a-zA-Z]*/g)   // ^[^a-zA-Z]+ to include the case when 
                                               // the string doesn't begin with a letter
)

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

3 Comments

This is missing the first empty string entry.
@TimBiegeleisen Yeah. Not sure how critical it is.
@Psidom, Not critical!!! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.