文章目录
指定位置清除空格(左、右、全部)
- 指定位置清除空格(左、右、全部)
- 去除字符串所有空格(最常用)
- 去除字符串所有空格(强烈推荐)
- 这则表达式解析
function removeSpaces(paramsString, type) { paramsString = String(paramsString); type = Number(type); if (!paramsString || !type) throw new Error('参数有误'); switch (type) { case 1: // 去除字符串所有的空格 paramsString = paramsString.replace(/\s*/g, ""); break; case 2: // 去除字符串两头的空格 paramsString = paramsString.replace(/^\s*|\s*$/g, ""); break; case 3: // 去除字符串左侧的空格 paramsString = paramsString.replace(/^\s*/, ""); break; case 4: // 去除字符串右侧的空格 paramsString = paramsString.replace(/(\s*$)/g, ""); break; case 5: // 去除字符串两头的空格 paramsString = paramsString.trim(); break; case 6: // 去除字符串左侧的空格 paramsString = paramsString.trimLeft(); break; case 7: // 去除字符串右侧的空格 paramsString = paramsString.trimRight(); break; default: throw new Error('出错啦'); break; } return paramsString; } console.log(removeSpaces(' Hello World ', 1)); console.log(removeSpaces(' Hello World ', 2)); console.log(removeSpaces(' Hello World ', 3)); console.log(removeSpaces(' Hello World ', 4)); console.log(removeSpaces(' Hello World ', 5)); console.log(removeSpaces(' Hello World ', 6)); console.log(removeSpaces(' Hello World ', 7)); console.log(removeSpaces(' Hello World ', 8));去除字符串所有空格(最常用)
function trim(str) { let reg = /[\t\r\f\n\s]*/g; if (typeof str === "string") return str.replace(reg,""); throw new Error(`${typeof str} is not the expected type, but the string type is expected.`); } console.log(trim(" abc d e f g ")); // abcdefg去除字符串所有空格(强烈推荐)
function trimAll(ele) { if (typeof ele === "string") { return ele.split(/[\t\r\f\n\s]*/g).join(""); } else { throw new Error(`${typeof ele} is not the expected type, but the string type is expected.`); } } console.log(trimAll(" 1 23 865 6 ")); // 1238656这则表达式解析
1、\f匹配换页字符 2、\n匹配换行字符 3、\r匹配回车符字符 4、\t匹配制表字符Tab 5、\v匹配垂直制表符