trim

  1. let stringValue = " hello world ";
  2. let trimmedStringValue = stringValue.trim();
  3. console.log(stringValue); // " hello world "
  4. console.log(trimmedStringValue); // "hello world"

正则替换

去除字符串内所有的空格:str = str.replace(/\s/g,””);
去除字符串内两头的空格:str = str.replace(/^\s
|\s$/g,””);
去除字符串内左侧的空格:str = str.replace(/^\s
/,””);
去除字符串内右侧的空格:str = str.replace(/(\s*$)/g,””);

  1. var str = " 6 6 ";
  2. var str_1 = str.replace(/\s*/g,"");
  3. console.log(str_1); //66
  4. var str = " 6 6 ";
  5. var str_1 = str.replace(/^\s*|\s*$/g,"");
  6. console.log(str_1); //6 6//输出左右侧均无空格
  7. var str = " 6 6 ";
  8. var str_1 = str.replace(/^\s*/,"");
  9. console.log(str_1); //6 6 //输出右侧有空格左侧无空格
  10. var str = " 6 6 ";
  11. var str_1 = str.replace(/(\s*$)/g,"");
  12. console.log(str_1); // 6 6//输出左侧有空格右侧无空格