Trim spaces from start and end of string

前端 未结 14 1517
情歌与酒
情歌与酒 2020-11-28 01:56

I am trying to find a way to trim spaces from the start and end of the title string. I was using this, but it doesn\'t seem to be working:

title = title.repl         


        
14条回答
  •  天命终不由人
    2020-11-28 02:38

    a recursive try for this

    function t(k){ 
        if (k[0]==' ') {
            return t(k.substr(1,k.length));
        } else if (k[k.length-1]==' ') {
            return t(k.substr(0,k.length-1));
        } else {
            return k;
        }
    }
    

    call like this:

    t("      mehmet       "); //=>"mehmet"
    

    if you want to filter spesific chars you can define a list string basically:

    function t(k){
        var l="\r\n\t "; //you can add more chars here.
        if (l.indexOf(k[0])>-1) {
            return t(k.substr(1,k.length));
        } else if (l.indexOf(k[k.length-1])>-1) {
            return t(k.substr(0,k.length-1));
        } else {
            return k;
        }
    }
    

提交回复
热议问题