Trim string in JavaScript?

后端 未结 20 2434
不知归路
不知归路 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条回答
  •  Happy的楠姐
    2020-11-21 07:08

    I had written this function for trim, when the .trim() function was not available in JS way back in 2008. Some of the older browsers still do not support the .trim() function and i hope this function may help somebody.

    TRIM FUNCTION

    function trim(str)
    {
        var startpatt = /^\s/;
        var endpatt = /\s$/;
    
        while(str.search(startpatt) == 0)
            str = str.substring(1, str.length);
    
        while(str.search(endpatt) == str.length-1)
            str = str.substring(0, str.length-1);   
    
        return str;
    }
    

    Explanation: The function trim() accept a string object and remove any starting and trailing whitespaces (spaces,tabs and newlines) and return the trimmed string. You can use this function to trim form inputs to ensure valid data to be sent.

    The function can be called in the following manner as an example.

    form.elements[i].value = trim(form.elements[i].value);
    

提交回复
热议问题