0

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!

1
  • You're using ^ and $ along with the m modifier. So does this mean that you only want to match when the [#some text goes here#] is the only thing on the line? Commented Feb 7, 2012 at 15:47

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@EOB: If it doesn't work for you, then you havent' properly described the result you want.
Aha, now it works! Dont know what the problem was ... I had the same just with [[] instead of \[ ... propably some tiny mistake somewhere, anyway, it works now, thanks!
1

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

1 Comment

[[] is the same as \[, isnt it?
0

This should capture the text between hashes (e.g., "some text here"):

var reg = /[^\[]*\[#([^\#]+)#\]/gims

Comments

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.