---- AI试用 ---域名问题某些图片和js资源无法访问,导致一些代码实例无法运行!(代码里gzui.net换成momen.vip即可)

格式化处理字符串

前端开发 蚂蚁 1592℃ 0评论

http://www.10qianwan.com/articledetail/522943.html

//格式化处理字符串
//ecDo.formatText('1234asda567asd890')
//result:"12,34a,sda,567,asd,890"
//ecDo.formatText('1234asda567asd890',4,' ')
//result:"1 234a sda5 67as d890"
//ecDo.formatText('1234asda567asd890',4,'-')
//result:"1-234a-sda5-67as-d890"
function formatText(str, size, delimiter) {
 var _size = size || 3, _delimiter = delimiter || ',';
 var regText = '\\B(?=(\\w{' + _size + '})+(?!\\w))';
 var reg = new RegExp(regText, 'g');
 return str.replace(reg, _delimiter);
}
//字符替换*,隐藏手机号或者身份证号等
//replaceStr(字符串,字符格式, 替换方式,替换的字符(默认*))
//ecDo.replaceStr('18819322663',[3,5,3],0)
//result:188*****663
//ecDo.replaceStr('asdasdasdaa',[3,5,3],1)
//result:***asdas***
//ecDo.replaceStr('1asd88465asdwqe3',[5],0)
//result:*****8465asdwqe3
//ecDo.replaceStr('1asd88465asdwqe3',[5],1,'+')
//result:"1asd88465as+++++"
//repeatstr(str->字符串, count->次数)
//util.repeatstr('123',3)
//"result:123123123"
function repeatStr(str, count) {
    var text = '';
    for (var i = 0; i < count; i++) {
        text += str;
    }
    return text;
};
Vue.filter('replaceString',function(str, regArr, type, ARepText){
    // console.log('repeatStr',repeatStr);
    str = str.toString();
    var regtext = '',
     Reg = null,
     replaceText = ARepText || '*';
     //repeatStr是在上面定义过的(字符串循环复制),大家注意哦
     if (regArr.length === 3 && type === 0) {
     regtext = '(\\w{' + regArr[0] + '})\\w{' + regArr[1] + '}(\\w{' + regArr[2] + '})'
     Reg = new RegExp(regtext);
     var replaceCount = repeatStr(replaceText, regArr[1]);
     return str.replace(Reg, '$1' + replaceCount + '$2')
     }
     else if (regArr.length === 3 && type === 1) {
     regtext = '\\w{' + regArr[0] + '}(\\w{' + regArr[1] + '})\\w{' + regArr[2] + '}'
     Reg = new RegExp(regtext);
     var replaceCount1 = repeatStr(replaceText, regArr[0]);
     var replaceCount2 = repeatStr(replaceText, regArr[2]);
     return str.replace(Reg, replaceCount1 + '$1' + replaceCount2)
     }
     else if (regArr.length === 1 && type === 0) {
     regtext = '(^\\w{' + regArr[0] + '})'
     Reg = new RegExp(regtext);
     var replaceCount = repeatStr(replaceText, regArr[0]);
     return str.replace(Reg, replaceCount)
     }
     else if (regArr.length === 1 && type === 1) {
     regtext = '(\\w{' + regArr[0] + '}$)'
     Reg = new RegExp(regtext);
     var replaceCount = repeatStr(replaceText, regArr[0]);
     return str.replace(Reg, replaceCount)
     }
});

转载请注明:有爱前端 » 格式化处理字符串

喜欢 (10)or分享 (0)