2

I have this piece of code:

_regex = /((?<!placeholder)\w+(?:\s*=\s*(?:"[^"]*"|'[^']*')))/;     
imgTag = imgTag.replaceAll(_regex, ' ');

Have also tried this instead:

imgTag = imgTag.replace( new RegExp( /((?<!placeholder)\w+(?:\s*=\s*(?:"[^"]*"|'[^']*')))/, "gi" ), ' ');

But my code never gets passed this line:

_regex = /((?<!placeholder)\w+(?:\s*=\s*(?:"[^"]*"|'[^']*')))/;     

Or this line:

imgTag = imgTag.replace( new RegExp( /((?<!placeholder)\w+(?:\s*=\s*(?:"[^"]*"|'[^']*')))/, "gi" ), ' ');

So the problem is in my RegEx, right?

I can't see it, can anyone please shed a light?

Thanks!

Bernardo Oliveira
  • 818
  • 1
  • 14
  • 30
  • possible duplicate of [RegEx match open tags except XHTML self-contained tags](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Amber Oct 10 '11 at 20:52
  • Your usage of `RegExp` is completely wrong, but yes, your regular expression is not correct either: `SyntaxError`. JavaScript does not know about lookbehinds `?<!`. – Felix Kling Oct 10 '11 at 20:53
  • Could be. This is the first time I'm having more contact with RegExes. I'm using O'Reilly's Regular Expressions Cookbook to pick up some things, but definitely still have a lot to learn about these guys. What would you say is "completely wrong" about that RegEx? And thanks about the lookbehind tip! – Bernardo Oliveira Oct 10 '11 at 21:02

2 Answers2

2

Javascript doesn't support lookbehinds. You can't write this:

(?<!placeholder)

Use a lookahead instead:

((?!placeholder).{11}|^.{0,10})

You'll need to adjust your replacement string too, because this matches extra characters just before the start of what you want to replace.


Also this won't work: var regex = new Regexp(/.../, "gi");

Write this instead: var regex = /.../gi;

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • thanks, that was indeed my problem! And about the `new Regexp(/.../)` code, it's because I wanted the `gi` flags, or there's another way to do that with the `replace` function? Thanks again! – Bernardo Oliveira Oct 10 '11 at 21:05
  • @BeOliveira: If you are using `RegExp`, you have to use a string. See https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions – Felix Kling Oct 10 '11 at 21:12
  • @FelixKling: Thanks again! I'm really enjoying RegEx's, still trying to get a general understanding, though. I used `regexp = /((?!placeholder)\w+(?:\s*=\s*(?:"[^"]*"|'[^']*')))/gi;` instead and it worked. But now I know how to do the same with `RegExp`. Thanks for the pointers! – Bernardo Oliveira Oct 10 '11 at 21:18
2

JavaScript does not support look-behind patterns. (That's the (?< pattern ) part.)

Pointy
  • 405,095
  • 59
  • 585
  • 614