从大HTML文件中提取javascript变量

时间:2014-07-26 19:46:45

标签: javascript ruby regex

我有一个带有javascript的HTML的巨型源文件我想从javascript内容中提取一些信息。考虑到我有一个类似以下的文件

<h1>Hello World</h1>
<script type="text/javascript">something useless</script>
<script type="text/javascript">var gmaps_vars = {FullAddress: "Rio de Janeiro, Rio de Janeiro, Brasil", GeoLocation: {"lng":-43.187554,"lat":-22.9470974}}</script>

我如何提取纬度和经度?

2 个答案:

答案 0 :(得分:1)

如何使用正则表达式:

m = /GeoLocation: \{"lng":(-?\d+\.\d+),"lat":(-?\d+\.\d+)\}/.match(html)
lng = m[1]
lat = m[2]

答案 1 :(得分:0)

尝试

html

<h1>Hello World</h1>
<script type="text/javascript">var a;</script>
<script type="text/javascript" id="vars">var gmaps_vars = {"FullAddress": "Rio de Janeiro, Rio de Janeiro, Brasil", "GeoLocation": {"lng":-43.187554,"lat":-22.9470974}}</script>

JS

$(function() {
    var coords = [];
    $.post(url, function(data, textStatus, jqxhr) {
        $.each($(data), function(index, value) {
            if ($(value).is("#vars")) {
              coords.push(JSON.parse($(value).text().replace(/var|gmaps_vars|\=/g, "")).GeoLocation);
              console.log(coords[0].lng + "\n" + coords[0].lat);
            };
        });
    });
});

jsfiddle http://jsfiddle.net/guest271314/HzPFg/