JavaScript之trim函数的实现
2020-12-16 本文已影响0人
小遁哥
函数功能等同String.prototype.trim
,空白字符不只是" "
测试数据
console.log('wx', '|' + able('12') + '|');
console.log('wx', '|' + able(' 1 1 2 2 ') + '|');
console.log('wx', '|' + able(' 1 2 ') + '|');
console.log('wx', '|' + able('1 2 ') + '|');
console.log('wx', '|' + able(' 1 2') + '|');
console.log('wx', '|' + able(' ') + '|');
console.log('wx', '|' + able(' ') + '|');
通过正则表达式
console.log('wx', '|' + able('\n 1\n 2 \n') + '|');
function able(str) {
const pattern = /^\s*|\s*$/g;
return str.replace(pattern, '');
}
function able(str = "") {
const pattern = /^\s*([\s\S]*?)\s*$/g;
return pattern.exec(str)[1] || '';
}
function able(str) {
return str.substring(
Math.max(str.search(/\S/), 0),
str.search(/\S\s*$/) + 1,
);
}
function able(str) {
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
为什么是\s\s*
而不是\s*
,我想是出于性能上面的衡量,更多:https://www.cnblogs.com/rubylouvre/archive/2009/09/18/1568794.html,这个超链接会让你感触良多,且行且珍惜。
以下不借助正则表达式的操作,通常在面试中会出现
通过数组的pop
(尾部移除)和shift
(首部移除)
能在开发中用好这种特性是不错的,也是倾向于这种考察,立马想到数据结构的特性
function able(str = '') {
const arr = [...str],
len = str.length;
while (true) {
if (arr[0] === ' ') {
arr.shift();
} else {
break;
}
}
while (true) {
if (arr[arr.length - 1] === ' ') {
arr.pop();
} else {
break;
}
}
return arr.join('');
}
利用字符串的substring
方法,第一次for
循环确认起始位置,第二次for循环确认结束位置,需要注意全部都是空格的情况,需要输出""
只能说不失为一种办法,通过特定的方式锻炼逻辑思维是不错的,好比平常用右手吃饭的人,被要求使用左手。
function able(str = '') {
let start = 0,
end = 0,
len = str.length;
for (let i = 0; i < len; i++) {
start = i;
if (str[i] !== ' ') {
break;
}
}
if (start === len - 1) {
return '';
}
for (let i = len - 1; i >= 0; i--) {
end = i + 1;
if (str[i] !== ' ') {
break;
}
}
return str.substring(start, end);
}
按照上面的思路,想把两个循环合并为一个,必须保证更新start
时,前面的全是空格(isBeforeAllSpace
),更新end
时,后面全是空格(isAfterAllSpace
),至少要新增两个标识符
function able(str = '') {
let start = 0,
len = str.length,
isBeforeAllSpace = true,
isAfterAllSpace = true,
end = 0;
for (let i = 0; i < len; i++) {
const beforeChar = str[i],
afterChar = str[len - i - 1];
if (isBeforeAllSpace && beforeChar !== ' ') {
start = i;
isBeforeAllSpace = false;
}
if (isAfterAllSpace && afterChar !== ' ') {
end = len - i;
isAfterAllSpace = false;
}
if (!isAfterAllSpace && !isBeforeAllSpace) {
break;
}
}
return str.substring(start, end);
}
无需对全部是空格的情况单独处理(strart
为0,end
也为0),因为无论是strart
和end
都是在出现不为空格时才更新值
通过!isAfterAllSpace && !isBeforeAllSpace
提前结束循环
本文将持续更新
关注专题 前端便利店 https://www.jianshu.com/c/c3f77a86d9a5 ,帮您省时省力!