1

I'm trying to match the text "foo" between the two brackets in this following statement:

Expected [foo] but Recieved [__]

I'm then trying to replace the text with "...". When I run the following code I get an invalid grouping error in JavaScript. When I run the expression in Regexr it works the way I expect it to.

var text = $("#assertion").html().replace( /(?<=Expected \[).*(?=\] )/,"...");

http://jsfiddle.net/bittersweetryan/VcraW/

1
  • You can solve this problem by not using lookbacks. Just include the lookback text in the regex as regular text to match with parens around it and then use $1 in your replacement string to put it back into the replacement. Commented Nov 25, 2011 at 16:04

2 Answers 2

6

Javascript regexes don't understand lookbacks (the ?<=). You need to match the Expected [ part explicitely:

replace(/(Expected \[)[^\]]*/, "$1...")

The $1 is to avoid retyping the "Expected [" part and I changed the rest of the regex a bit to avoid greedy matching with .*

http://jsfiddle.net/VcraW/2/

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

1 Comment

+1 for the 25 seconds you were faster and having exactly the same thoughts than me.
3

Because javascript does not support look behind assertions.

You can work around by putting this in a capturing group and using this in the replacement

.replace( /(Expected \[).*(?=\] )/,"$1...");

The content of the first pair of brackets is stored in the capturing group 1 and you can get this back using $1

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.