Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 648
hossein hayati Avatar asked Apr 11 '19 15:04

hossein hayati


People also ask

Can you remove all duplicate characters in the string?

We can remove the duplicate characters from a string by using the simple for loop, sorting, hashing, and IndexOf() method. So, there can be more than one way for removing duplicates.

Which of the following command will help to remove consecutive duplicates?

Remove consecutive duplicate lines in a file using Uniq command. If you use 'uniq' command without any arguments, it will remove all consecutive duplicate lines and display only the unique lines.


1 Answers

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
like image 186
anubhava Avatar answered Oct 08 '22 19:10

anubhava