js 去除空格
时间: 2023-07-23 15:15:25 浏览: 64
在 JavaScript 中,可以通过正则表达式和字符串方法来去除字符串中的空格。以下是两种常见的方法:
1. 使用 replace() 方法和正则表达式去除空格:
```javascript
let str = " hello world ";
str = str.replace(/\s+/g, "");
console.log(str); // "helloworld"
```
2. 使用 trim() 方法去除字符串两端的空格:
```javascript
let str = " hello world ";
str = str.trim();
console.log(str); // "hello world"
```
如果您想去除字符串中间的空格,可以使用 replace() 方法和正则表达式来替换空格为一个空字符串:
```javascript
let str = " hello world ";
str = str.replace(/\s/g, "");
console.log(str); // "helloworld"
```