将一串字符串中叠字符删除

1.普通写法:
不追求效率的话,其实这样写更加安全

var str = "aabbcccccddefggg";
var str_tmp = ''
var simbol_same = ''
for (var i = 0; i < str.length; i++){
    if (str[i] == simbol_same) {
        continue;
    }
    simbol_same = str[i];
    str_tmp += simbol_same;
}
alert(str_tmp)

2.正则写法

var str = "aabbcccccddefggg";
str = str.replace(/(.)\1+/g, function (sameletter) { return sameletter[0] });
alert(str)

测试地址:
https://www.typescriptlang.org/play/

你可能感兴趣的:(将一串字符串中叠字符删除)