0

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

3
  • I've tried to split the string by lines, then by ','. So I have array of substrings. Then I need to extracts tags from each substring. It's a little bit easy than from initial string, but I still don't know how to do it :) Commented Mar 4, 2013 at 2:18
  • so what result are you after? Something like {first: "tag",second: "tag (tags sepearated by commas}",third: "tag",fourth: "tag (tags separated by space)",tag:"from new line (it's just one tag)", tag1tag2tag3 : "(tags can follow each other)"} Commented Mar 4, 2013 at 2:38
  • just a plain array of tags Commented Mar 4, 2013 at 2:44

1 Answer 1

2

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.
)
Sign up to request clarification or add additional context in comments.

5 Comments

it doesn't grab the last tag "tag3"
ok, I can append an additional \n at the end of the string :)
You need to add $ to your lookahead (i.e. (?=\s*([\+,\n]|$))), but +1
@mVChr Good call, updated. @Iidar, adding the $ is a better way that adding an extra \n.

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.