求一个分割字符串的方法?

代码如下

const str = "#CJSHDKLCNASLKJOIJSVCLXCJDLJSCSA4LJF7OR5IEU9FDJCP";

str长度不固定, 在 # 后面的字符串长度加起来是2的倍数, 需要拆分得到如下的数组

[ "CJ", "SH", "DK", "LC"... ]
阅读 2.1k
4 个回答
str.match(/[^#]{2}(?=[^#]*$)/g)

用split()方法和map()方法:

const str = "#CJSHDKLCNASLKJOIJSVCLXCJDLJSCSA4LJF7OR5IEU9FDJCP";
const result = str.slice(1).split('').map((char, i, arr) => {
  return i % 2 === 0 ? arr.slice(i, i + 2).join('') : null;
}).filter(Boolean);

用Array.from()方法:

const str = "#CJSHDKLCNASLKJOIJSVCLXCJDLJSCSA4LJF7OR5IEU9FDJCP";
const result = Array.from({length: str.length / 2 - 1}, (_, i) => str.slice(i * 2 + 1, i * 2 + 3));

用循环:

const str = "#CJSHDKLCNASLKJOIJSVCLXCJDLJSCSA4LJF7OR5IEU9FDJCP";
let result = [];
for (let i = 1; i < str.length; i += 2) {
  result.push(str.slice(i, i + 2));
}
const LEN = 2; // 你可以灵活控制,比如以后你要按 3 个字符分了就改成 3
str.split('#')[1].match(new RegExp(`.{1,${LEN}}`, 'g'));
function splitStringAfterHash(str) {
  if (!str || typeof str !== 'string' || !str.includes('#')) {
    return [];
  }

  const startIndex = str.indexOf('#') + 1;
  const hashContent = str.slice(startIndex);
  const pairs = [];

  for (let i = 0; i < hashContent.length; i += 2) {
    pairs.push(hashContent.substr(i, 2));
  }

  return pairs;
}

const str = "#CJSHDKLCNASLKJOIJSVCLXCJDLJSCSA4LJF7OR5IEU9FDJCP";
const result = splitStringAfterHash(str);

console.log(result);
推荐问题
logo
Microsoft
子站问答
访问
宣传栏