José Carlos
José Carlos

Reputation: 1015

Result of javascript regular expression not understood

When I eval (in javascript) [I meant, used string.match()]:

<!--:es-->Text number 1<!--:--><!--:en-->text 2<!--:-->

using

/<!--:es-->(.|\n)*?<!--:-->/

I get as match:

Text number 1,1

I mean, it adds a comma and repeats the last character. Does anybody know why this happens?

PS. text could have carriage return, that is why i used (.|\n).

Thanks a lot.

Upvotes: 1

Views: 105

Answers (3)

Jeff
Jeff

Reputation: 2871

Some research has shown me that the . can't match newlines in javascript.

I'd rewrite your regex this way:

/<!--:es-->[\s\S]*?<!--:-->/

This will avoid the problem you saw, as it excludes the capture group.

And ghoppe is right: use RegExp.

Upvotes: 0

ghoppe
ghoppe

Reputation: 21794

When I eval (in javascript)

Don't. Use RegExp

Eval() evaluates any ECMAScript, you don't want to do this if you don't have 100% control over the input.

Upvotes: 2

Mike Samuel
Mike Samuel

Reputation: 120516

The result of a regular expression match is an array.

The zero-th element of the array is the whole match : "Text number 1" The first element of the array is the contents of the first group, in this case "1" since the * is outside the parentheses.

When the array is converted to a string, you get the contents with commas in between.

Upvotes: 4

Related Questions