0

I'm trying to split a String in JavaScript that is separated by commas but, I have extra commas within the portions of the string I want to keep together. Here's an example:

var str = 'A. This is one part, B. This is the, tricky part., C. Final portion';

My desired result is an array like this one:

var arrayAfterSplit = [
    'A. This is one part',
    'B. This is the, tricky part',
    'C. Final portion'
];

I'm trying with Regex but, no success until now, I'd appreciate any help guys. Thanks.

2 Answers 2

4

How about :

 str.split (/, (?=[A-Z]\. )/)

Explanation :

the , find those characters in source string, the (?=[A-Z]\. ) then test if the following characters a capital letter followed by a full-stop and a single space. This is a "look ahead" test and the characters there are just checked not matched by the regular expression.

So the string is split by the occurrence of , but only if the following characters are a capital letter etc.

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

1 Comment

You're my hero dude, thanks. Could you explain me a little bit what's happening there?
0

try the Below one

(?:,\s+(?=[A-Z]\.))

,\s+ - Comma (,) should be followed by one or more white space 


 (?=[A-Z]\.) positive Look ahead to check the above condition follows by the Capital Letter and (.)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.