vue 字符串分割
时间: 2023-07-24 18:04:30 浏览: 424
可以使用 JavaScript 内置的 `split()` 方法来实现字符串分割。
例如,如果要将字符串按照某个字符进行分割,可以这样做:
```javascript
const str = "hello,world";
const arr = str.split(",");
console.log(arr); // ["hello", "world"]
```
其中,`split()` 方法的参数为分隔符,上述代码中使用了逗号作为分隔符。
如果要将字符串按照某个长度进行分割,可以这样做:
```javascript
const str = "hello world";
const arr = str.match(/.{1,5}/g);
console.log(arr); // ["hello", " worl", "d"]
```
其中,使用了正则表达式 `/.{1,5}/g`,表示匹配任意字符,长度为 1 到 5 的字符串。`match()` 方法返回一个数组,包含匹配到的字符串。
还可以使用 `slice()` 方法进行分割,例如:
```javascript
const str = "hello world";
const arr = [];
for(let i = 0; i < str.length; i += 5) {
arr.push(str.slice(i, i+5));
}
console.log(arr); // ["hello", " worl", "d"]
```
其中,使用了 `slice()` 方法,从字符串中截取指定长度的子串。循环遍历字符串,每次截取 5 个字符作为一个子串,存入数组中。