Home > database >  How to split combined string into multiple strings in array?
How to split combined string into multiple strings in array?

Time:11-18

How can I split this array with commas? I have multiple arrays

[ "LeadershipPress" ]
[ "BusinessLeaderLeadershipPress" ]
[ "LeaderLeadershipPoliticsPress" ]
etc.

scraper.scrapeListingPages('article.article', (item) => { 
    var categories = $(item).find('a[rel = "category tag"]').text().split();
    console.log(categories);
    categories.forEach(function(i){
       $(i).find('a[rel = "category tag"]')
       console.log(i);
    })
});

Right now my output in the console is

Array [ "BusinessLeaderLeadershipPress" ]
BusinessLeaderLeadershipPress

I want to split the categories into an array with commas without having to use separator, limits or regex because I have multiple random arrays.

Is there a way I can use a forEach or for loop to accomplish this?

The result I want is [ "Business, Leader, Leadership, Press" ]

Thanks

CodePudding user response:

You could split a string with a look ahead for an uppercase letter.

const
    string = 'BusinessLeaderLeadershipPress',
    result = string.split(/(?=[A-Z])/);

console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related