1

This is the code I'm using to try to replace empty commas with zero:

let str = '<C><P /><Z><S><S P=",,0.3,0.2,,,," L="195" X="256" H="32" Y="306" T="0" /><S P=",,0.3,0.2,,,," L="146" X="587" H="87" Y="257" T="0" /><S P=",,0.3,0.2,,,," L="50" X="333" H="45" Y="82" T="0" /></S><D /><O /></Z></C>';
let repl = str.replace(/,,/g, ",0,");

The result is:

<C><P /><Z><S><S P=",0,0.3,0.2,0,,0," L="195" X="256" H="32" Y="306" T="0" /><S P=",0,0.3,0.2,0,,0," L="146" X="587" H="87" Y="257" T="0" /><S P=",0,0.3,0.2,0,,0," L="50" X="333" H="45" Y="82" T="0" /></S><D /><O /></Z></C>

I expected something like: <... P="0,0,0.3,0.2,0,0,0,0" .../>

How to do it?

3
  • You are replacing two comma with a zero with comma before and after it. That's what you got there. Can you explain why did you expect something else? Commented Jun 30, 2020 at 6:35
  • 1
    var repl = str.replace(',,', '0,'); this ?? Commented Jun 30, 2020 at 6:37
  • 1
    Add replace ", to "0, And ," to ,0" Commented Jun 30, 2020 at 6:40

2 Answers 2

3

How about:

repl = repl.replace(/P=",/g, 'P="0,')
repl = repl.replace(/,"/g, ',0"')
Sign up to request clarification or add additional context in comments.

Comments

1

Although accepted answer does the job, following is a bit generic than that.

let str = '<C><P /><Z><S><S P=",,0.3,0.2,,,," L="195" X="256" H="32" Y="306" T="0" /><S P=",,0.3,0.2,,,," L="146" X="587" H="87" Y="257" T="0" /><S P=",,0.3,0.2,,,," L="50" X="333" H="45" Y="82" T="0" /></S><D /><O /></Z></C>';

let str = str.replace(/,+/g, ',').replace(/",|,"/g,'"')

Explanation:

  1. Replace one or more occurrences of comma with comma

    str.replace(/,+/g, ',')

  2. Now there will not be any duplicates but words within quites will have trailing commas which can be removed using following

str.replace(/",|,"/g,'"')

Demo:

 let str = '<C><P /><Z><S><S P=",,0.3,0.2,,,," L="195" X="256" H="32" Y="306" T="0" /><S P=",,0.3,0.2,,,," L="146" X="587" H="87" Y="257" T="0" /><S P=",,0.3,0.2,,,," L="50" X="333" H="45" Y="82" T="0" /></S><D /><O /></Z></C>';

 let output =  str.replace(/,+/g, ',').replace(/",|,"/g,'"')
 
 console.log("input:", str);
 console.log("output:",output);

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.