最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin5PV0评论

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.

Post a comment

comment list (0)

  1. No comments so far