我有一个数组列表,如下所示:
0: "1 Trenchard Road, , , , Saltford, Bristol, Avon"
1: "10 Trenchard Road, , , , Saltford, Bristol, Avon"
2: "11 Trenchard Road, , , , Saltford, Bristol, Avon"
3: "12 Trenchard Road, , , , Saltford, Bristol, Avon"
我想删除中间的逗号:
, , ,
我正在使用 Lodash 并考虑使用 _.compact()
但这似乎并没有让我有任何进展。
让我知道你的想法
更新
var addressArray = getAddressData.data.Addresses;
scope.items = _.compact(addressArray);
console.log(scope.items);
最佳答案
您可以使用 JavaScript Array#map
使用正则表达式删除多余的逗号。
arr.map(e => e.replace(/(,\s*)+/, ','));
ES5 等效项:
arr.map(function (e) {
return e.replace(/(,\s*)+/, ',');
});
正则表达式 (,\s*)+
将搜索一个或多个以任意数量的空格分隔的逗号。
var arr = ["1 Trenchard Road, , , , Saltford, Bristol, Avon", "10 Trenchard Road, , , , Saltford, Bristol, Avon", "11 Trenchard Road, , , , Saltford, Bristol, Avon", "12 Trenchard Road, , , , Saltford, Bristol, Avon"];
arr = arr.map(e => e.replace(/(,\s*)+/, ', '));
console.log(arr);
document.getElementById('result').innerHTML = JSON.stringify(arr, 0, 4);
<pre id="result"></pre>
关于javascript - 如何从字符串数组中删除逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35150910/