Trim spaces from start and end of string

前端 未结 14 1496
情歌与酒
情歌与酒 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 02:34

    This is what is suggested by JavaScript Architect/Guru Douglas Crockford.

    String.method('trim', function (  ) {
        return this.replace(/^\s+|\s+$/g, '');
    });
    

    Note: you have to define "method" for Function.prototype.

    Alternatively

    String.prototype.trim = function () {
       return this.replace(/^\s+|\s+$/g, '');
    };
    
    title.trim();    // returns trimmed title
    

    Observation

    In recent browsers, the trim method is included by default. So you don't have to add it explicitly.

    Major browsers Chrome, Firefox, Safari etc. supports trim method. Checked in Chrome 55.0.2883.95 (64-bit), Firefox 51.0.1 (64-bit), Safari 10.0 (12602.1.50.0.10).

提交回复
热议问题