Ildar
Ildar

Reputation: 343

Regular expressions in JS (select tags from string)

I have this string:

some description +first tag, +second tag (tags separated by commas)
+third tag +fourth tag (tags separated by space)
+tag from new line (it's just one tag)
+tag1+tag2+tag3 (tags can follow each other)

How can I select all tag names from this string?

1) Tag can contain several words, 2) tag always starts with + sign, 3) tag ends with either next tag, or newline, or comma

Upvotes: 0

Views: 172

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161457

I'd give this a shot:

var str = "some description +first tag, +second tag\n" +
   "+third tag +fourth tag\n" +
   "+tag from new line\n" +
   "+tag1+tag2+tag3";
var tags = str.match(/\+[^+,\n\s].+?(?=\s*[\+,\n]|$)/g);

this results in tags with this:

[ '+first tag',
  '+second tag',
  '+third tag',
  '+fourth tag',
  '+tag from new line',
  '+tag1',
  '+tag2',
  '+tag3' ]

To elaborate:

\+          // Starts with a '+'.
[^+,\n\s]   // Doesn't end immedatedly (empty tag).
.+?         // Non-greedily match everything.
(?=         // Forward lookahead (not returned in match).
  \s*       // Eat any trailing whitespace.
  [\+,\n]|$ // Find tag-ending characters, or the end of the string.
)

Upvotes: 2

Related Questions