Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
815 views
in Technique[技术] by (71.8m points)

regex - Remove consecutive duplicate characters in a string javascript

I have some string like 11122_11255_12_223_12 and the output I wish to have is this: 12_125_12_23_12
I already looked at this and also this and etc
but there are not what I want as I described above.

actually, I used here for my purpose but something is wrong.

here is my code :

var str='11222_12_111_122_542_1212333_122';
var result = str.replace(/(1{2,}|2{2,}|3{2,}|4{2,}|5{2,}|6{2,}|7{2,}|8{2,}|9{2,})/g,'$1');
console.log(result);

and it is not working. it gives me the exact input in output.

as I mentioned above I have some string like 11122_11255_12_223_12 and the output I wish to have is this: 12_125_12_23_12, it means between the underlines is a number, and for each number if there are two or more digits next to each other(ex:223 has two 2), I want to keep just one of them.
thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use capture group and back-reference:

result = str.replace(/(.)1+/g, '$1')

RegEx Demo

  • (.): Match any character and capture in group #1
  • 1+: Match 1+ characters same as in capture group #1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...