Trim string in JavaScript?

后端 未结 20 2782
不知归路
不知归路 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条回答
  •  萌比男神i
    2020-11-21 06:52

    You can do it using the plain JavaScript:

    function trimString(str, maxLen) {
    if (str.length <= maxLen) {
    return str;
    }
    var trimmed = str.substr(0, maxLen);
    return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…';
    }
    
    // Let's test it
    
    sentenceOne = "too short";
    sentencetwo = "more than the max length";
    
    console.log(trimString(sentenceOne, 15));
    console.log(trimString(sentencetwo, 15));
    

提交回复
热议问题