Reputation: 97
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
Upvotes: 2
Views: 672
Reputation: 1
without having to use separator, limits or regex because I have multiple random arrays.
A simple approach using for-loop
with algorithm taking Consideration that string starts with Uppercase:
Looping through characters of the string
if char is not UPPERCASE accumelate chars to variable word
, until encounter Uppercase letter, then push it in res
Array.
const string = "BusinessLeaderLeadershipPress";
let i = 1;
let character = "";
let word = string[0];
const res = [];
while (i <= string.length) {
character = string.charAt(i);
if (character == character.toUpperCase()) {
res.push(word);
word = character;
} else {
word += character;
}
i++;
}
console.log(res); //['Business', 'Leader', 'Leadership', 'Press']
Upvotes: 2
Reputation: 386560
You could split a string with a look ahead for an uppercase letter.
const
string = 'BusinessLeaderLeadershipPress',
result = string.split(/(?=[A-Z])/);
console.log(result);
Upvotes: 1