0

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?

2
  • Replace /,(?=,|$)/g with ,0. Commented May 11, 2021 at 1:03
  • 1
    Your idea is correct, but the mistake you made is the regex consumes 2 commas at once. So it won't replace the last comma if there are odd number of commas. Using a lookahead solves this problem. Commented May 11, 2021 at 1:07

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! You saved me lot of time and frustration.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.