使用jquery

时间:2017-06-15 12:10:38

标签: javascript jquery regex replace

我有一个字符串如下

var data = "10 Watkin Terrace, , , , , Northampton, Northamptonshire";

如何使用jquery删除上述数据中的额外“,”

3 个答案:

答案 0 :(得分:1)

纯粹的javascript:

var addresses = data['Addresses'];

for (i in addresses) {
  var address = addresses[i];
  var parts = address.split(',');

  var str = [];
  for (j in parts) {
    var part = parts[j];
    if (part.trim()) {
        final.push(part);
    }
  }
  data['Addresses'][i] = str.join(',');
}

console.log(data);

答案 1 :(得分:1)

Pure JavaScript:

data = "10 Watkin Terrace, , , , , Northampton, Northamptonshire";
data = data.replace(/(,\s)+/g, '$1');

答案 2 :(得分:0)

选中此项以删除不必要的字符串

String.prototype.replaceWith = function (str1, str2, ignore) {
        return  this.replace(new RegEenter code herexp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\\$&"), `enter code here`(ignore ? "gi" : "g")), (typeof(str2) == "string") ? str2.replace(/\$/g, "$$$$") : str2);
    };
  function simplifyData(dataObject){
     for(var key in dataObject){         
        if(Array.isArray(dataObject[key])){
            dataObject[key].forEach(function(val,ind){
                if(typeof dataObject[key][ind] == 'string'){
                    dataObject[key][ind] =  dataObject[key][ind].replaceWith(",","");
                } 
            })
        }else if(typeof dataObject[key] == 'string'){{
            dataObject[key] =  dataObject[key].replaceWith(",","");
        }    
        }        
    }
    return dataObject;
  }

   var data = {
        "Latitude": 52.24593734741211,
        "Longitude": -0.891636312007904,
        "Addresses":
          ["10 Watkin Terrace, , , , , Northampton, Northamptonshire",
           "12 Watkin Terrace, , , , , Northampton, Northamptonshire",
           "14 Watkin Terrace, , , , , Northampton, Northamptonshire",
           "16 Watkin Terrace, , , , , Northampton, Northamptonshire",
           "18 Watkin Terrace, , , , , Northampton, Northamptonshire"]};

           var _returnData = simplifyData(data);
           console.log(_returnData)

Fiddle for this demo