1

I have a regular expression in node.js which matches some strange things. Look at this:

var regex = new RegExp('(<\?%)|(%\?>)', 'g');
console.log('<tag><?%text%?></tag>'.match(regex));

Leads to [ '>', '%', '%', '>', '>' ] and I don't understand why.

The purpose was to match <?% or %?> and it works perfectly fine on https://regex101.com/.

2 Answers 2

3

That is because you haven't escaped \. It should be \\.

Press Ctrl + Shift + I , go in Console and paste the following code.

var regex = new RegExp('(<\\?%)|(%\\?>)', 'g');
console.log('<tag><?%text%?></tag>'.match(regex));
Sign up to request clarification or add additional context in comments.

4 Comments

@SLaks: Your reason is correct. I was showing why OP's code was not working since `` was unescaped.
That actually does work though... am I missing something @SLaks?
@sweaver2112: Ow the damn typo ! Not in good faculties of vision at this time or day.
@remus: i would guess he's saying that a regex literal makes for a smaller, simpler regex without the need to escape the backslash. I'd probably not make such a blanket statement there, however, as noob's solution seems ok to me.
2

Your backslashes are being swallowed by string escaping.

You should use a regex literal instead: /(<\?%)|(%\?>)/g

2 Comments

Your badges are breaking CSS. Should inform on Meta !
Yeah, noob is right, that's like a bug. Also there is another weird thing. SLaks has 500k rep and I never seen him here at all .. Where have you been until now? :-)

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.