您当前的位置: 首页 >  Java

暂无认证

  • 0浏览

    0关注

    92582博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

JavaScript去除字符串空格、throw、switch、case、break、default

发布时间:2022-05-14 23:37:18 ,浏览量:0

文章目录
  • 指定位置清除空格(左、右、全部)
  • 去除字符串所有空格(最常用)
  • 去除字符串所有空格(强烈推荐)
  • 这则表达式解析
指定位置清除空格(左、右、全部)
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匹配垂直制表符

关注
打赏
1653961664
查看更多评论
立即登录/注册

微信扫码登录

0.4331s