我有几千行代码Javascript
:
var myCoordinates = [
new google.maps.LatLng(11.11111,22.222222),
new google.maps.LatLng(33.33333,44.444444),
new google.maps.LatLng(55.55555,66.666666),
//thousands of lines
];
我需要将上面的代码格式化为没有空格(a.k.a到字符串我可以复制到我的PHP代码):
[["lat"=>11.11111,"lng"=>22.22222],["lat"=>33.33333,"lng"=>44.44444],["lat"=>55.55555,"lng"=>66.66666],/*etc*/];
我尝试过但失败了:
document.getElementById('format-submit').onclick = function() {
var textareaValue = document.getElementById('format-textarea').value;
var findA = 'var myCoordinates = ';
var rA = new RegExp( findA, 'g' );
var resultA = textareaValue.replace( rA, '' );
//I get this error on this line:
//Uncaught SyntaxError: Invalid regular expression: /new google.maps.LatLng(/: Unterminated group
// |
// V
var findB = 'new google.maps.LatLng(';
var rB = new RegExp(findB, 'g');
var resultB = resultA.replace(rB, '["lat" => ');
var findC = '),';
var rC = new RegExp(findC, 'g');
var resultC = resultB.replace(rC, '],');
var findD = ')';
var rD = new RegExp(findD, 'g');
var finalResult = resultC.replace(rD, ']');
textareaValue = finalResult;
};
速度或性能不是问题,我只需要:
JS
代码复制到textarea 问题:
如何更换其中包含各种字母,特殊字符等的部分字符串?
(可能的错误原因,对吧?)
答案 0 :(得分:3)
我相信这就是你要找的东西。
document.getElementById('format-submit').onclick = function() {
var textarea = document.getElementById('format-textarea');
textarea.value = textarea.value
.replace(/^[^\[]+/,'')
.replace(/^.*\(([\d.]+),([\d.]+)\)(,)?$/gm,'["lat" => $1, "lng" => $2]$3')
.replace(/\s+/g,'');
};
<textarea id="format-textarea" rows="7" cols="46">var myCoordinates = [
new google.maps.LatLng(11.11111,22.222222),
new google.maps.LatLng(33.33333,44.444444),
new google.maps.LatLng(55.55555,66.666666)
];</textarea><br>
<input type="button" id="format-submit" value="Format textarea">
答案 1 :(得分:0)
试试这段代码,这会给你你想要的东西
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
var myCoordinates = [
new google.maps.LatLng(11.11111,22.222222),
new google.maps.LatLng(33.33333,44.444444),
new google.maps.LatLng(55.55555,66.666666),
//thousands of lines
];
var fullJson = [];
for(var i = 0; i < myCoordinates.length; i++) {
var temp = {};
var pos = myCoordinates[i];
temp['lat'] = pos.lat();
temp['lng'] = pos.lng();
fullJson.push(temp);
}
var str_json = JSON.stringify(fullJson);
$.post('index.php', str_json, function(result) {
console.log(result);
});
</script>
<?php
if (isset($_POST)) {
$str_json = file_get_contents('php://input');
echo '<pre>';
print_r($str_json);
echo '</pre>';
}