js字符串切割,替换函数封装

//数据类型转字符 tostring
var n = 12;
var n = n.toString();
//console.log(n);
//console.log(typeof n);

//字符分割 str.split(通过指定字符分割,返回的最大长度)
var string = 'ssdgsfys和你ss好我是林和你ss是的回复ss和你是玩儿u好ss宿舍的积分'; 
var str = split(string,'ss',4);
console.log(str);

var m = string.split('ss',4);
console.log(m);
/**
 *str    字符串
 *tr    指定字符
 *len    长度(选填)
 * */
function split(str,tr=null, len=null)
{
        var arr = [];
        var num = str.length;
        var lent = tr.length;
        var res = 0;
        for(var i =0;i<num;i++){
            if(tr == null){
                arr.push(str[i]);
            }else{
                var string = '';
                for(var k=0;k<lent;k++){
                    string += str[i+k];
                }
                if(string == tr){
                   if(i==0){res+=lent;continue;}
                    var p = i - res;
                    if(i == (num-1))p+=1;
                    arr.push(str.substr(res,p));
                    res = i+lent;
                    if(arr.length==len)break;
                    continue;
                }

            }
        }
    if(arr.length !== len)arr.push(str.substr(res,num-res));
    return arr;
}

//字符替换  replace
var string = "linfenghelloeprd";
//console.log(string.replace('ll','&&'));
//console.log(replace(string,'ll','&&'));
/**
 *str    字符串
 *req    需要替换的字符
 *list    替换的值
 * */
function replace(str,req,list)
{
    var lenr = req.length;
    var len = str.length;
    var i = 0;
    var data = '';
    for(i;i < len;i++){
        var k = 0;
        var string = '';
        for(k;k < lenr; k++){
            var n = i+k;
            string += str[n];
        }
        if(string == req){
            data += list;
            i = i+lenr;
        }
        data += str[i]
    }
    return data;
}

 

posted @ 2019-09-19 14:22  时间掉飞机  阅读(1010)  评论(1编辑  收藏  举报