写一个方法去掉字符串中的空格,要求传入不同的类型分别能去掉前、后、前后、中间的空格。
var str = ' a b c d e f g ';
function removeSpace(value, type) {
var headPattern = /^s+/g;
var tailPattern = /s+$/g;
var headAndTailPattern = /^s+|s+$/g;
var middlePattern = /(S)s+(S)/g;
var pattern = /s+/g;
if (type === 'head') {
return value.replace(headPattern, '');
} else if (type === 'tail') {
return value.replace(tailPattern, '');
} else if (type === 'head_and_tail') {
return value.replace(headAndTailPattern, '');
} else if (type === 'middle') {
while (middlePattern.exec(value)) {
value = value.replace(middlePattern, '$1$2');
}
return value;
} else {
return value.replace(pattern, '');
}
}