1

I have a string that looks like this:

var str = "'1vK3KfqgSHqv5Y0066FnIY',#41,$,$,(#149,#488,#862,#945,#1028,#1249),#114";

Usually I would just:

str.split(",");

But this will result in:

[
    "'1vK3KfqgSHqv5Y0066FnIY'", 
    "#41", 
    "$", 
    "$", 
    "(#149", 
    "#488", 
    "#862", 
    "#945", 
    "#1028", 
    "#1249)", 
    "#114"
]

Whereas the desired result is:

[
    "'1vK3KfqgSHqv5Y0066FnIY'", 
    "#41", 
    "$", 
    "$", 
    "(#149, #488, #862, #945, #1028, #1249)", 
    "#114"
]

How would I achieve this?

3
  • what if the string would be "'1vK3KfqgSHqv5Y0066FnIY',(#1,(#41,$),$,(#149,#488,#862,#945,#1028,#1249),#11),#114" ? How should look the expected result? Commented Jul 21, 2016 at 13:47
  • You'd need to write some sort of customer parser to account for parentheses. Commented Jul 21, 2016 at 13:53
  • @RomanPerekhrest In that case it would be an array consisting of 3 records: [ "'1vK3KfqgSHqv5Y0066FnIY'", "(#1,(#41,$),$,(#149,#488,#862,#945,#1028,#1249),#11)",‌ ‌​"#114" ] But I do not think the IFC STEP file (which this is based on) has that kind of structure. Commented Jul 21, 2016 at 13:55

1 Answer 1

3

Hi here would be a regex

str.match(/(\(.*?\)|[^\(,\s]+)(?=\s*,|\s*$)/g)

which results in

[ '\'1vK3KfqgSHqv5Y0066FnIY\'',
  '#41',
  '$',
  '$',
  '(#149,#488,#862,#945,#1028,#1249)',
  '#114' ]
Sign up to request clarification or add additional context in comments.

2 Comments

Provide demo to checking result.
Seems not everything had been copied right to Regexr, now it works. Thanks!

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.