string - Javascript: Replace Pipe with Commas in a packet - Stack Overflow

admin2025-04-26  16

I have string for example like this:

$K,86107,2,2,04,77.232323,86.330234,00000000000000,V,0,10,,,0,0,410,04,1e29,a16d,7000,0,1537|0|0|4762|0|0,1,0,,,,*22

If I use : str.replace('|',",") it only replaces the first pipe with ma.

If I use : str.replace(/|/g,",") the resulting string is:

,$,K,,,8,6,1,0,7,,,2,,,2,,,0,4,,,7,7,.,2,3,2,3,2,3,,,8,6,.,3,3,0,2,3,4,,,0,0,0,0,0,0,0,0,0,0,0,0,0,0,,,V,,,0,,,1,0,,,,,,,0,,,0,,,4,1,0,,,0,4,,,1,e,2,9,,,a,1,6,d,,,7,0,0,0,,,0,,,1,5,3,7,|,0,|,0,|,4,7,6,2,|,0,|,0,,,1,,,0,,,,,,,,,*,

What I want is:

$K,86107,2,2,04,77.232323,86.330234,00000000000000,V,0,10,,,0,0,410,04,1e29,a16d,7000,0,1537,0,0,4762,0,0,1,0,,,,*22

Any suggestions?

I have string for example like this:

$K,86107,2,2,04,77.232323,86.330234,00000000000000,V,0,10,,,0,0,410,04,1e29,a16d,7000,0,1537|0|0|4762|0|0,1,0,,,,*22

If I use : str.replace('|',",") it only replaces the first pipe with ma.

If I use : str.replace(/|/g,",") the resulting string is:

,$,K,,,8,6,1,0,7,,,2,,,2,,,0,4,,,7,7,.,2,3,2,3,2,3,,,8,6,.,3,3,0,2,3,4,,,0,0,0,0,0,0,0,0,0,0,0,0,0,0,,,V,,,0,,,1,0,,,,,,,0,,,0,,,4,1,0,,,0,4,,,1,e,2,9,,,a,1,6,d,,,7,0,0,0,,,0,,,1,5,3,7,|,0,|,0,|,4,7,6,2,|,0,|,0,,,1,,,0,,,,,,,,,*,

What I want is:

$K,86107,2,2,04,77.232323,86.330234,00000000000000,V,0,10,,,0,0,410,04,1e29,a16d,7000,0,1537,0,0,4762,0,0,1,0,,,,*22

Any suggestions?

Share Improve this question edited Aug 20, 2015 at 8:20 sahil gupta 2,34913 silver badges14 bronze badges asked Aug 20, 2015 at 8:16 AnakooterAnakooter 3276 silver badges17 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You need to escape the | use str.replace(/\|/g, ",");

As joyBlanks said, you can use a greedy regular expression to do a full replace. You can also use split() and join()...

str = str.split("|").join(",");

split() splits the string into an array, with the given delimiter, and then join() joins the array elements with the given delimiter, returning a string.

I'd say use the regular expression, but it's worth knowing this method too.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745648354a312014.html

最新回复(0)