js the trim function to achieve

js method spaces on both sides of the string is not removed. To achieve this effect is currently thought of in two ways, one is a regular match, is also a loop on both sides of the string to determine whether a space.
Of course, we must pay attention to distinguish between English space, Chinese space, tab spaces, the concept of continuous space, here only in English spaces, for example.

Regular way:

function trim(str) {
    return str.replace(/^\s*/,"");//^符号是开始
    return str.replace(/\s*$/,"");//$符号是结束
    return str.replace(/(^\s*)|(\s*$)/g,""); //两边
}

Cycle way:

function trim(str) {
    let startIndex = -1;
    for(let i = 0; i < str.length; i++) {
        if(str.charAt(i) !== ' ') {
            startIndex = i;
            break;
        }
    }
    if(startIndex === -1) { //全空格
        return '';
    }
    let endIndex = str.length - 1;
    for(let i = endIndex; i >= 0; i--) {
        if(str.charAt(i) !== ' ') {
            endIndex = i;
            break;
        }
    }
    return str.slice(startIndex, endIndex);
}

Guess you like

Origin www.cnblogs.com/bhoold/p/12072714.html