Trim spaces from start and end of string

前端 未结 14 1316
情歌与酒
情歌与酒 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

    Here is my current code, the 2nd line works if I comment the 3rd line, but don't work if I leave it how it is.

    var page_title = $(this).val().replace(/[^a-zA-Z0-9\s]/g, '');
    page_title = page_title.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    page_title = page_title.replace(/([\s]+)/g, '-');
    
    0 讨论(0)
  • 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;
        }
    }
    
    0 讨论(0)
  • 2020-11-28 02:43
    var word = " testWord ";   //add here word or space and test
    
    var x = $.trim(word);
    
    if(x.length > 0)
        alert('word');
    else
        alert('spaces');
    
    0 讨论(0)
  • 2020-11-28 02:45

    If using jQuery is an option:

    /**
     * Trim the site input[type=text] fields globally by removing any whitespace from the
     * beginning and end of a string on input .blur()
     */
    $('input[type=text]').blur(function(){
        $(this).val($.trim($(this).val()));
    });
    

    or simply:

    $.trim(string);
    
    0 讨论(0)
  • 2020-11-28 02:45

    ECMAScript 5 supports trim and this has been implemented in Firefox.

    trim - MDC

    0 讨论(0)
  • 2020-11-28 02:51

    Here is some methods I've been used in the past to trim strings in js:

    String.prototype.ltrim = function( chars ) {
        chars = chars || "\\s*";
        return this.replace( new RegExp("^[" + chars + "]+", "g"), "" );
    }
    
    String.prototype.rtrim = function( chars ) {
        chars = chars || "\\s*";
        return this.replace( new RegExp("[" + chars + "]+$", "g"), "" );
    }
    String.prototype.trim = function( chars ) {
        return this.rtrim(chars).ltrim(chars);
    }
    
    0 讨论(0)
提交回复
热议问题