Trim string in JavaScript?

后端 未结 20 2358
不知归路
不知归路 2020-11-21 06:27

How do I trim a string in JavaScript? That is, how do I remove all whitespace from the beginning and the end of the string in JavaScript?

相关标签:
20条回答
  • 2020-11-21 07:10

    Use the Native JavaScript Methods: String.trimLeft(), String.trimRight(), and String.trim().


    String.trim() is supported in IE9+ and all other major browsers:

    '  Hello  '.trim()  //-> 'Hello'
    


    String.trimLeft() and String.trimRight() are non-standard, but are supported in all major browsers except IE

    '  Hello  '.trimLeft()   //-> 'Hello  '
    '  Hello  '.trimRight()  //-> '  Hello'
    


    IE support is easy with a polyfill however:

    if (!''.trimLeft) {
        String.prototype.trimLeft = function() {
            return this.replace(/^\s+/,'');
        };
        String.prototype.trimRight = function() {
            return this.replace(/\s+$/,'');
        };
        if (!''.trim) {
            String.prototype.trim = function() {
                return this.replace(/^\s+|\s+$/g, '');
            };
        }
    }
    
    0 讨论(0)
  • 2020-11-21 07:10

    Here's a very simple way:

    function removeSpaces(string){
    return string.split(' ').join('');
    }
    
    0 讨论(0)
  • 2020-11-21 07:11

    Don't know what bugs can hide here, but I use this:

    var some_string_with_extra_spaces="   goes here    "
    console.log(some_string_with_extra_spaces.match(/\S.*\S|\S/)[0])
    

    Or this, if text contain enters:

    console.log(some_string_with_extra_spaces.match(/\S[\s\S]*\S|\S/)[0])
    

    Another try:

    console.log(some_string_with_extra_spaces.match(/^\s*(.*?)\s*$/)[1])
    
    0 讨论(0)
  • 2020-11-21 07:14

    The trim from jQuery is convenient if you are already using that framework.

    $.trim('  your string   ');
    

    I tend to use jQuery often, so trimming strings with it is natural for me. But it's possible that there is backlash against jQuery out there? :)

    0 讨论(0)
  • 2020-11-21 07:16

    Simple version here What is a general function for JavaScript trim?

    function trim(str) {
            return str.replace(/^\s+|\s+$/g,"");
    }
    
    0 讨论(0)
  • 2020-11-21 07:16

    I know this question has been asked three years back.Now,String.trim() was added natively in JavaScript.For an instance, you can trim directly as following,

    document.getElementById("id").value.trim();
    
    0 讨论(0)
提交回复
热议问题