metrobalderas
metrobalderas

Reputation: 5240

JS+Regexp: Match anything except if it's between [[ ]]

I've got a <textarea> that will be basically a list of names, so I set a function to replace the spaces between the names for a new line.

Now I need to specify that two or more spaces between names are in fact part of the same element.
IE:

John Lucas [[Laurie Vega]] [[Daniel Deer]] Robert

Should turn to

John
Lucas
[[Laurie Vega]]
[[Daniel Deer]]
Robert

So now my regexp $("textarea").val().toString().replace(\ \g, '\n'); is broken as it will add a new line before Vega and Deer.

I need to replace anything that's not in between [ and ]. I just made the opposite and tried to negate it, but it doesn't seem to work:

// Works
$("textarea").val().toString().match(/\[([^\]]*)\]/g));
// Am I using the ! operand wrong?
$("textarea").val().toString().match(/!\[([^\]]*)\]/g));

I'm a little lost. I tried matching and then replacing, but that way I won't be able to recover my original string. So I have to match anything outside double brackets and replace the space.

Upvotes: 1

Views: 379

Answers (2)

Gavin Brock
Gavin Brock

Reputation: 5087

If there is a chance that your names contain non alphabetic characters ("Jim-bo O'Leary"?), you may prefer match anything that is not a '[' or a space using /[^[ ]/.

You can then join the matched strings to get the new line effect.

$("textarea").val().toString().match(/([^\[ ]+|\[\[[^\]]*\]\])/g).join("\n");

Upvotes: 1

Jonathan Feinberg
Jonathan Feinberg

Reputation: 45344

The exclamation point has no particular meaning in a regex.

What you're looking for is either (that means the | operator) a sequence of letters

[A-Za-z]+

or two brackets, followed by some non-closing-brackets, followed by two closing brackets

\[\[[^\]]+\]\]

So

$("textarea").val().toString().match(/[A-Za-z]+|\[\[[^\]]+\]\]/g)

Upvotes: 0

Related Questions