正则表达式不能转义特殊字符

时间:2018-11-26 16:34:20

标签: javascript leaflet

如果我愿意

if(childMarkers.length > 0) {
  const [lat, lng] = `${ childMarkers[0].getLatLng() }`.match(/(-?\d+.\d*)/gi);   
  const requiredString = `${ lat } ${ lng }`;
  console.log(requiredString);
}  

我明白了

45, 9)

我应该得到

45, 9

为了能够将其分成2个input .val(),如下所示:

    if(childMarkers.length > 0) {
      const [lat, lng] = `${ childMarkers[0].getLatLng() }`.match(/(-?\d+.\d*)/gi);   
      const requiredString = `${ lat } ${ lng }`;
      $("#longiTude").attr("value",lat);
      $("#latiTude").attr("value", lng);  
    }

完整代码:

// We draw the markers
function drawMarkers() {
  var i;
  for (i = 0; i < longitude.length; ++i) {
    pair=[ parseFloat( latitude[i] ) , parseFloat(  longitude[i]  ) ]
    count.push(  pair );
    $("#searchNations").removeAttr("disabled");
    $(this).attr("disabled", "disabled");
    var myYears = $('#years').val();
    $("#ajax-load-more ul").attr("data-meta-value", myYears);
  };
  if(stopAjax == false) {
    console.log("ciao");
    L.MarkerCluster.include({
      spiderfy: function(e) {
        var childMarkers = this.getAllChildMarkers();
        this._group._unspiderfy();
        this._group._spiderfied = this;
        // If there are any childMarkers
        if(childMarkers.length > 0) {
          // Match the lat and lng numbers from the string returned by getLatLng()
          const [lat, lng] = `${ childMarkers[0].getLatLng() }`.match(/(-?\d+(\.\d+)?)/g);   
          // Construct the required string value from the extracted numbers
          const requiredString = `${ lat } ${ lng }`;
          // Use requiredString to populate the value attribute of the input field in OP
          $("#longiTude").attr("value",lat);
          $("#latiTude").attr("value", lng);  
          console.log(requiredString);
          //submitSearchForm();
        }
      },
      unspiderfy: function() {
        this._group._spiderfied = null;
      }
    });

    var mcg = L.markerClusterGroup().addTo(map);
    circles = new L.MarkerClusterGroup();

    for (var i = 0; i < count.length; i++) {
      var a = count[i];
      var circle = new L.CircleMarker([a[0], a[1]]);
      circles.addLayer(circle);
      circle.on('click', function (e) {
        var curPos = e.target.getLatLng();
        $("#longiTude").val(curPos.lat);
        $("#latiTude").val(curPos.lng);
        console.log(curPos.lng);
        //submitSearchForm();
      });
    }
    // we add the markers to the map
    map.addLayer(circles);
    // we empty the arrays for the future calls
    count = [];
    longitude = [];
    // we set again stopAjax var to true to reset
    stopAjax = true;   
  }
}

1 个答案:

答案 0 :(得分:1)

您的正则表达式应为:/(-?\d+(\.\d+)?)/g,以便仅匹配数字,后跟可选的小数部分。

const regex = /(-?\d+(\.\d+)?)/g;

console.log("L.LatLng {lat: 45, lng: 9.1}".match(regex));