Home > other >  How to parse this string into an array of string
How to parse this string into an array of string

Time:07-26

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"]

CodePudding user response:

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));

CodePudding user response:

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);

CodePudding user response:

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))

CodePudding user response:

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