简体   繁体   English

如何将此字符串解析为字符串数组

[英]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这是我目前的尝试,但正如您所看到的,它没有过滤掉前面的 -(dash),在每个单词后包含一个空字符,并将“自动驾驶汽车”分成两个不同的元素

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

You could always map and trim and filter .你总是可以maptrim 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));

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

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.您可以尝试使用下一个正则表达式: (\r|\n)- 并从开头或结尾删除空元素,您可以在将其设为数组之前使用.trim()。 console.log(keywords.split(/(\r|\n)-/).trim().filter((element) => element)) console.log(keywords.split(/(\r|\n)-/).trim().filter((element) => element))

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM