使用 JavaScript 将字符串分解为固定长度的块并删除空格
问题
我们需要编写一个 JavaScript 函数,该函数以一个可能包含空格的字符串句子作为第一个参数,并以一个数字作为第二个参数。
我们的函数应首先删除字符串中的所有空格,然后将字符串分解为由第二个参数指定数量的块。
所有字符串块应具有相同的长度,但最后一部分除外,在某些情况下,最后一部分可能有不同的长度。
例子
以下为代码 −
const num = 5;
const str = 'This is an example string';
const splitString = (str = '', num = 1) => {
str = str.replace(/\s/g,'');
const arr = [];
for(let i = 0; i < str.length; i += num){
arr.push(str.slice(i,i + num));
};
return arr;
};
console.log(splitString(str, num));输出
[ 'Thisi', 'sanex', 'ample', 'strin', 'g' ]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP