12

I try test string using regexp in JavaScript. Correct string looking like:

<script charset="utf-8">new DGWidgetLoader({"width":640,"height":600,"borderColor":"#a3a3a3","pos":{"lat":46.00650100065259,"lon":11.263732910156252,"zoom":9}

I want test that "width", "height" looks like xxx or xxxx, and "lat", "lon" looks like x{1,2}.x*, zoom looks like x{1,2}

I try use this regex

/<script charset="utf-8">new DGWidgetLoader(/{"width":[0-9]{3,4},"height":[0-9]{3,4},"borderColor":"#a3a3a3","pos":\{"lat":[0-9]{1,2}.[0-9]+,"lon":[0-9]{1,2}.[0-9]+,"zoom":[0-9][0-9]}//

with String.search(), but got error SyntaxError: Invalid regular expression: /<script charset="utf-8">new DGWidgetLoader(/{"width":[0-9]{3,4},"height":[0-9]{3,4},"borderColor":"#a3a3a3","pos":{"lat":[0-9]{1,2}.[0-9]+,"lon":[0-9]{1,2}.[0-9]+,"zoom":[0-9][0-9]}//: Unterminated group

How can i parse script tag that looking like below?

Andrew Kochnev
  • 956
  • 2
  • 7
  • 10

2 Answers2

20

You should escape (, {, } and . with \:

/<script charset="utf-8">new DGWidgetLoader\(\{"width":[0-9]{3,4},"height":[0-9]{3,4},"borderColor":"#a3a3a3","pos":\{"lat":[0-9]{1,2}\.[0-9]+,"lon":[0-9]{1,2}\.[0-9]+,"zoom":[0-9][0-9]\}/
Sébastien
  • 2,236
  • 2
  • 20
  • 28
2

I think the problem is here:

... DGWidgetLoader(/{ ....

Should be:

... DGWidgetLoader\(\{ ...

And the final slash is unnecessary in this case.

EDIT: Also, escape the final } mark and other special characters. So:

/<script charset="utf-8">new DGWidgetLoader\(\{"width":[0-9]{3,4},"height":[0-9]{3,4},"borderColor":"#a3a3a3","pos":\{"lat":[0-9]{1,2}\.[0-9]+,"lon":[0-9]{1,2}\.[0-9]+,"zoom":[0-9][0-9]\}/

Also there is a small logic issue here: your zoom rule requires exactly two numerals while in practice it can be either one or two. You should consider fixing that.

Ynhockey
  • 3,845
  • 5
  • 33
  • 51