0

I have strings in my program that are like so:

var myStrings = [

"[asdf] thisIsTheText",
"[qwerty]  andSomeMoreText",
"noBracketsSometimes",
"[12345]someText"

];

I want to capture the strings "thisIsTheText", "andSomeMoreText", "noBracketsSometimes", "someText". The pattern of inputs will always be the same, square brackets with something in them (or maybe not) followed by some spaces (again, maybe not), and then the actual text I want.

How can I do this?

Thanks

JDS
  • 16,388
  • 47
  • 161
  • 224
  • 2
    [*what have you tried?*](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – zzzzBov Sep 12 '12 at 20:48
  • You can use the string .split() method. See here: http://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript – Matthew Blancarte Sep 12 '12 at 20:49
  • @zzzzBov Sorry, just had to ask for a free-bee, I've never used regex properly before. Definitely working to understand the answers though, so next time I have an initial attempt. Yes I agree with your sentiment though. – JDS Sep 12 '12 at 21:14

2 Answers2

1

This should get you started:

/(?:\[[^]]*])?\s*(\w+)/
alan
  • 4,752
  • 21
  • 30
1

One approach:

var actualTextYouWant = originalString.replace(/^\[[^\]]+\]\s*/, '');

This will return a copy of originalString with the initial [...] and whitespace removed.

ruakh
  • 175,680
  • 26
  • 273
  • 307
  • Thanks, I just had no starting point. I've been debugging your answer with a regex guide so I understand. I've found that .* can work after matching the first \[ – JDS Sep 12 '12 at 21:12
  • Probably should be `/^\[[^\]]*\]\s*/` (`*` instead of `+`), but that only matters if OP ends up with a string along the lines of `'[] fooBar'`. – zzzzBov Sep 12 '12 at 21:34
  • @zzzzBov: You may be right, but the OP said "square brackets with something in them", so I took that to mean `+`. – ruakh Sep 12 '12 at 21:45
  • @YoungMoney: `.*` will only work if you know that there will be no other `]`s in the string. (But even if there could be, you can change `[^\]]+` to `.+?` if you prefer. The `?` makes it nongreedy.) – ruakh Sep 12 '12 at 21:46