Tyler Kim
Tyler Kim

Reputation: 379

How to parse this string into an array of string

How can I parse this string into an array of string?

This is my current attempt, but as you can see it is not filtering out the -(dash) in front, includes an empty character after each word, and separates "Self-Driving Cars" into two different elements

keywords = "\n\n-AI \n-Tools \n-Food \n-Safety \n-Objects \n-High Shelves \n-Monitoring \n-Movement \n-Lawns \n-Windows \n-Bathing \n-Hygiene \n-Repetitive \n-Physical \n-Self-Driving Cars \n-Smartphones \n-Chatbots"

console.log(keywords.split(/\r?\n?-/).filter((element) => element))

===console results=== 
["
", "AI ", "Tools ", "Food ", "Safety ", "Objects ", "High Shelves ", "Monitoring ", "Movement ", "Lawns ", "Windows ", "Bathing ", "Hygiene ", "Repetitive ", "Physical ", "Self", "Driving Cars ", "Smartphones ", "Chatbots"]

This is the correct result I want

["AI", "Tools", "Food", "Safety", "Objects", "High Shelves", "Monitoring", "Movement", "Lawns", "Windows", "Bathing", "Hygiene", "Repetitive", "Physical", "Self-Driving Cars", "Smartphones", "Chatbots"]

Upvotes: 0

Views: 51

Answers (4)

Mochamad Faishal Amir
Mochamad Faishal Amir

Reputation: 102

console.log(keywords.split(/\r?\n?-/).map((element) => element.trim()).filter(element => element))

Upvotes: 0

Gabriel
Gabriel

Reputation: 61

You can try using the next regular expression: (\r|\n)- and to get rid of the empty element from beginning or end you can use .trim() before making it array. console.log(keywords.split(/(\r|\n)-/).trim().filter((element) => element))

Upvotes: 0

Guy ABN
Guy ABN

Reputation: 11

I was able to solve this using the following:

// the starting string
let str = "\n\n-AI \n-Tools \n-Food \n-Safety \n-Objects \n-High Shelves \n-Monitoring \n-Movement \n-Lawns \n-Windows \n-Bathing \n-Hygiene \n-Repetitive \n-Physical \n-Self-Driving Cars \n-Smartphones \n-Chatbots";

// split the string into an array of strings
let arr = str.split("\n");

// remove empty strings
arr = arr.filter(s => s.length > 0);

// remove '-' from the beginning of each string
arr = arr.map(s => s.substring(1));

// print the array
console.log(arr);

Upvotes: 1

IT goldman
IT goldman

Reputation: 19521

You could always map and trim and filter.

var keywords = "\n\n-AI \n-Tools \n-Food \n-Safety \n-Objects \n-High Shelves \n-Monitoring \n-Movement \n-Lawns \n-Windows \n-Bathing \n-Hygiene \n-Repetitive \n-Physical \n-Self-Driving Cars \n-Smartphones \n-Chatbots"

var arr = keywords.split("\n")

console.log(arr.map(item => item.trim().slice(1)).filter(item => item));

Upvotes: 1

Related Questions