我的输入类似于以下字符串:
IN|1st Cross,1st Block,IN|282,Sector 19,IN|10th Floor,Winchester House,DN|id,fgh,FG|ag
我想要的应该是:
IN|1st Cross,1st Block IN|282,Sector 19 IN|10th Floor,Winchester House DN|id,fgh FG|ag
请问我如何达到上述效果?
答案 0 :(得分:1)
你去了:
function separateComaForCountry(str) {
// find a coma, that has any amount of letters after it that are not , nor | and then stop when you see either the end of the string or another |
var reg = /,([^|,]+(?:$|\|))/g;
return str.replace(reg, function(match, country){
return ' ' + country;
});
}
然后用您的用例调用该函数。
separateComaForCountry("IN|1st Cross,1st Block,IN|282,Sector 19,IN|10th Floor,Winchester House,DN|id,fgh,FG|ag");
// outputs IN|1st Cross,1st Block IN|282,Sector 19 IN|10th Floor,Winchester House DN|id,fgh FG|ag
答案 1 :(得分:0)
我看到你想用国家代码替换空格前的逗号。这就像删除“偶数位置”中的逗号一样。
您可以使用逗号分隔符拆分字符串以获取数组中的不同部分,然后使用reduce方法删除连接数组的条目。
const inputStr = 'IN|1st Cross,1st Block,IN|282,Sector 19,IN|10th Floor,Winchester House,DN|id,fgh,FG|ag';
function customStringSplit(inputString){
const splittedInputStr = inputString.split(',');
const resultStr = splittedInputStr.reduce(function(acc, val, index){
return (index%2 === 1 ? acc + ',' + val : acc + ' ' + val);
});
return resultStr;
}
console.log(customStringSplit(inputStr));
有关不同内置函数的更多信息,请参阅using String.prototype.split()上的Array.prototype.reduce和Mozilla Developer Network.