Richard Hovdsveen Richard Hovdsveen -4 years ago 84
Javascript Question

Splitting string with Regex with exceptions in Javascript

Been trying to split a string by [space] but with some exceptions in javascript, but only with partial success.

String:

Surname, Name (description) Category1 Surename, Name Category2 "Category3" " Cate gory4", category5 (category1)


Wanted output:

- Surname, Name (description)
- Category1
- Surename, Name
- Category2
- "Category3"
- " Cate gory4"
- category5 (category1)


Tried regex

\s+(?=([^"]*"[^"]*")*[^"]*$)(?=[^()]*(?:\(|$))(?=[^(])


Provisional output

- Surname,
- Name (description)
- Category1
- Category2
- "Category3"
- " Cate gory4",
- category5 (category1)


I cant find a way to make the exception for ", ".

Anyone who have an idea for solving this?

EDIT: Added an alternative string in string and output.

Best regards
Richard

Answer Source

You can use this regex based on alternation:

var str = 'Surname, Name (description) Category1 Category2 "Category3" " Cate gory4",    category5 (category1)';

var m = str.match(/\b\w[\w,\s]*\([^)]+\)|"[^"]*"|\b\S+/g);

console.log(m);

RegEx Demo

RegEx Breakup:

  • \b\w[\w,\s]*\([^)]+\) - Match some text followed by (...) OR
  • "[^"]*" - Match quoted string
  • \b\S+ - Match 1 or more non-space text

Output:

[
  "Surname, Name (description)",
  "Category1",
  "Category2",
  "\"Category3\"",
  "\" Cate gory4\"",
  "category5 (category1)"
]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download