简体   繁体   中英

Replace 2 characters inside a string in JavaScript

I have this string and I want to fill all the blank values with 0 between to , :

var initialString = 3,816,AAA3,aa,cc,bb,5.9,27,46,0.62,29,12,7,10,13.1,86,6.02,20,1.68,8,0.24,48,22,6.2,0.9,,,1,

I want this output:

var finalString = 3,816,AAA3,aa,cc,bb,5.9,27,46,0.62,29,12,7,10,13.1,86,6.02,20,1.68,8,0.24,48,22,6.2,0.9,0,0,1,0

I try to use replace

var newString = initialString.replace(/,,/g, ",0,").replace(/,$/, ",0");

But the finalString looks like this:
var initialString = 3,816,AAA3,aa,cc,bb,5.9,27,46,0.62,29,12,7,10,13.1,86,6.02,20,1.68,8,0.24,48,22,6.2,0.9,0,,1,0 Some coma are not replaced.

Can someone show me how to do it?

You can match a comma which is followed by either a comma or end of line (using a forward lookahead) and replace it with a comma and a 0 :

 const initialString = '3,816,AAA3,aa,cc,86,6.02,20,1.68,8,0.24,48,22,6.2,0.9,,,1,'; let result = initialString.replace(/,(?=,|$)/g, ',0'); console.log(result)

using split and join

 var str = "3,816,AAA3,aa,cc,bb,5.9,27,46,0.62,29,12,7,10,13.1,86,6.02,20,1.68,8,0.24,48,22,6.2,0.9,,,1,"; const result = str.split(",").map((s) => (s === ""? "0": s)).join(","); console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM