【发布时间】:2021-11-16 03:31:33
【问题描述】:
我使用 UrlFetchApp.fetch(url,options) 获得了有效的 HTML 代码。我感兴趣的部分看起来像
<script type="text/javascript">
var map = am4core.create("mapdiv", am4maps.MapChart);
map.geodata = am4geodata_worldLow;
map.projection = new am4maps.projections.Miller();
var polygonSeries = new am4maps.MapPolygonSeries();
polygonSeries.useGeodata = true;
map.series.push(polygonSeries);
// Configure series
var polygonTemplate = polygonSeries.mapPolygons.template;
polygonSeries.data = [{
"id": "AF",
"value0": "2",
"value3": 3.2,
"fill": am4core.color("#0C6175")
}, {
"id": "AL",
"value0": "2",
"value3": 2.5,
"fill": am4core.color("#0C6175")
}, {
"id": "DZ",
"name": "Algeria",
"value0": "1",
"value3": 3.2,
"fill": am4core.color("#68C2C3")
}];
polygonTemplate.propertyFields.fill = "fill";
</script>
您能否建议如何获取分配给 GAS 变量的 polygonSeries.data javascript 变量的值?除了逐行解析HTML,找到polygonSeries.data,然后解析直到我得到}];,我想不出任何办法,但我认为这不是最好的方法。
【问题讨论】:
-
您可以在How can I convert HTML code into a JSON object 尝试类似帖子的答案,或者尝试使用
regex类似var clean = htmlcontent.replace(/ /g,''); var regExp = new RegExp("polygonSeries.data=(.*)polygonTemplate", "s"); var data = regExp.exec(clean)[1]; var arr = data.split(/\r?\n/)的东西,然后清理并将数据放入数组或对象中。 -
我看不出stackoverflow.com/questions/60468365/… 会怎样。但是我使用了你的代码,在 6 行代码中我完成了我需要的。您要创建一个答案以便我接受吗?为什么我们需要去除空格?
-
当然,我将发布正则表达式方法作为答案。我很高兴快速正则表达式方法对您有用。我正在删除 html 代码中的所有空格,因为在我使用正则表达式进行测试时,当有多个空格时它不起作用。
标签: javascript google-apps-script html-parsing