Reputation: 3085
I have this JavaScript code:
var textareas = document.getElementsByTagName('textarea');
var content = textareas[0].value;
var reg = new RegExp(/^.*[[]#.+#[]].*$/mgi);
var res = content.match(reg); // always null
The content var contains a long multiline string that contains patterns like [#some text goes here#]
. I tested the regex with some online testing tools and it works against the string. Using the regex in JavaScript fails though - any idea why?
Thanks!
Upvotes: 0
Views: 285
Reputation: 34294
How about this?
var content = 'foo\nhead [#some text goes here#] tail\nbar';
var reg = new RegExp(/\[#.+#\]/mgi);
var res = content.match(reg);
On execution, res
contains the string '[#some text goes here#]'
.
Note that I have escaped [
and ]
. If they are not escaped, anything enclosed within them forms a character class.
Upvotes: 4
Reputation: 25091
This should capture the text between hashes (e.g., "some text here"):
var reg = /[^\[]*\[#([^\#]+)#\]/gims
Upvotes: 0
Reputation: 143204
You used [[]
to escape [
, which is fine, but you can't use []]
to escape ]
because it the first ]
ends the character class in the regex. This works fine:
/^.*\[#.+#\].*$/mgi
In the case that you only want the single block and not the entire line, use:
/\[#.+#\]/mgi
Upvotes: 1