You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用循环将拼接字符串拆分为逗号分隔数组(不使用正则/分隔符)

字符串拆分实现方案

核心实现逻辑

  • 遍历拼接字符串的每一个字符,检测到大写字符时,将此前累计的字符串作为一个完整单词存入结果数组,重新开始累计新单词
  • 遍历结束后把最后一个累计的单词补充进结果数组即可

修改后的完整代码

scraper.scrapeListingPages('article.article', (item) => { 
    // 获取原始类别字符串
    const rawCategory = $(item).find('a[rel = "category tag"]').text();
    const categories = [];
    let currentWord = '';
    // 遍历每个字符拆分
    for (let i = 0; i < rawCategory.length; i++) {
        const char = rawCategory[i];
        // 大写字符作为新单词的起始标识
        if (char === char.toUpperCase() && i !== 0) {
            categories.push(currentWord);
            currentWord = '';
        }
        currentWord += char;
    }
    // 补充最后一个未入数组的单词
    categories.push(currentWord);
    // 输出拆分结果
    console.log(categories);
    // 后续分类遍历处理
    categories.forEach(category => {
        console.log(category);
    })
});

输出效果

输入BusinessLeaderLeadershipPress时,输出结果为:

Array [ "Business", "Leader", "Leadership", "Press" ]

内容的提问来源于stack exchange,提问作者Sarah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 13:36:10