我在量角器脚本中有一个字符串'str',如下所示。我需要将所有'aaaa'替换为换行符,并且每个新行的开头都不应包含逗号。
var str="51 Cart Road #408, Missouri City, TX 77459aaaa,90 South Street, Southern Pines, NC 87-541aaaa,01 Cart Road #7708, Missouri City, TX 7659aaaa";
str=str.replace(/aaaa/g,"\n");
console.log(str);
所以我将得到的结果为
51 Cart Road #408, Missouri City, TX 77459
,90 South Street, Southern Pines, NC 87-541
,01 Cart Road #7708, Missouri City, TX 7659
但是我的目标是获得
51 Cart Road #408, Missouri City, TX 77459
90 South Street, Southern Pines, NC 87-541
01 Cart Road #7708, Missouri City, TX 7659
所以我怎么只能从新行中删除逗号。谢谢。
答案 0 :(得分:0)
var str="51 Cart Road #408, Missouri City, TX 77459aaaa,90 South Street, Southern Pines, NC 87-541aaaa,01 Cart Road #7708, Missouri City, TX 7659aaaa";
str=str.replace(/aaaa,?/g,"\n");
console.log(str);
答案 1 :(得分:0)
使用aaaa,
使用\n
var str="51 Cart Road #408, Missouri City, TX 77459aaaa,90 South Street, Southern Pines, NC 87-541aaaa,01 Cart Road #7708, Missouri City, TX 7659aaaa";
str = str.split('aaaa,').join('\n');
console.log(str);
编辑:看来上一个aaaa没有使用上面的代码删除。 更新:
使用aaaa
分割字符串
映射数组以删除第一个字符
使用\n
var str="51 Cart Road #408, Missouri City, TX 77459aaaa,90 South Street, Southern Pines, NC 87-541aaaa,01 Cart Road #7708, Missouri City, TX 7659aaaa";
str = str.split('aaaa').map(s => s.slice(1)).join('\n');
console.log(str);
答案 2 :(得分:0)
您可以使用匹配“ aaaa”或“ aaaa”的正则表达式,然后将其替换为“ \ n”
var str="51 Cart Road #408, Missouri City, TX 77459aaaa,90 South Street, Southern Pines, NC 87-541aaaa,01 Cart Road #7708, Missouri City, TX 7659aaaa";
str=str.replace(/aaaa,?/g,"\n");
console.log(str);
答案 3 :(得分:0)
var str="51 Cart Road #408, Missouri City, TX 77459aaaa,90 South Street, Southern Pines, NC 87-541aaaa,01 Cart Road #7708, Missouri City, TX 7659aaaa";
str = str.toString().replace(/aaaa,/g, '\n');
console.log(str);
确保在.replace()之前先添加.toString()