ForeveHG / Frontend-Daily-Interview

学习,尝试回答一些前端面试题
1 stars 0 forks source link

67. 写一个方法去掉字符串中的空格 #68

Open ForeveHG opened 3 years ago

ForeveHG commented 3 years ago

写一个方法去掉字符串中的空格,要求传入不同的类型分别能去掉前、后、前后、中间的空格

题目来自https://github.com/haizlin/fe-interview/issues/6

ForeveHG commented 3 years ago
function trim(str, position) {
    switch(position) {
        case 'all': 
            str = str.replace(/\s/g, '')
            break;
        case 'left':
            str = str.replace(/^[\s]*/, '')
            break;
        case 'right':
            str = str.replace(/[\s]*$/, '')
            break;
        case 'center':
            while(str.match(/\w\s+\w/)) {
                str = str.replace(/(\w)(\s+)(\w)/, `$1$3`)
            }
            break;
    }
    return str;
}