0

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"]
2
  • 2
    Split at /\s+\n+-/ Commented Jul 25, 2022 at 7:49
  • You could also just match(). keywords.match(/(?<=\n-).+[^\s]/g); Commented Jul 25, 2022 at 7:59

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.