Shazboticus S Shazbot
Shazboticus S Shazbot

Reputation: 1289

JavaScript regex match [[quote][/quote]]

var quote = 'some text here [[quote=bob]This is some text bob wrote[/quote]] other text here';

I'm trying to get [[quote=bob]This is some text bob wrote[/quote]].

I was using: match(/[[quote=(.*?)](.*?)[/quote]]/)[1]

but it gives me some text here [[quote=bob]This is some text bob wrote[/quot

Upvotes: 0

Views: 74

Answers (2)

Johnride
Johnride

Reputation: 8736

The problem here is that [ is a reserved character in regular expressions so you must escape it to use it as a "regular" character.

Here is a start for you, this will match [quote=bob] from your variable quote.

quote.match(/\[quote=[a-z]*\]/)

Here is the complete, correct and safe version.

string.match(/\[quote=[a-z]*\]([^\[]*)\[\/quote\]/)

Which will return the proper string including the surrounding [quote] tags as first result and only the inner string as second result.

I also used the [a-z] character class as you don't want to match anything after the = character.

Upvotes: 1

Johan Karlsson
Johan Karlsson

Reputation: 6476

Try this:

var quote = 'some text here [[quote=bob]This is some text bob wrote[/quote]] other text here';

console.log( quote.match(/(\[\[quote=(.*?)\](.*?)\[\/quote\]\])/) );
// [1] => "[[quote=bob]This is some text bob wrote[/quote]]"
// [2] => "bob"
// [3] => "This is some text bob wrote"

Upvotes: 3

Related Questions