删除字符串javascript中的连续重复字符 [英] Remove consecutive duplicate characters in a string javascript

查看:86
本文介绍了删除字符串javascript中的连续重复字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些类似 11122_11255_12_223_12 的字符串我希望得到的输出是: 12_125_12_23_12
我已经看过

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.

这是我的代码:

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.

如上所述,我有一些类似 11122_11255_12_223_12 的字符串我希望得到的输出是: 12_125_12_23_12 ,这意味着下划线之间是一个数字,并且对于每个数字,如果有两个或多个彼此相邻的数字(例如:223有两个2),我只想保留其中之一.
谢谢.

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.

推荐答案

您可以使用捕获组和反向引用:

You can use capture group and back-reference:

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

RegEx演示

  • (.):匹配任何字符并捕获#1组
  • \ 1 + :匹配捕获组#1中的1+个字符
  • (.): Match any character and capture in group #1
  • \1+: Match 1+ characters same as in capture group #1

这篇关于删除字符串javascript中的连续重复字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆