如何将此字符串解析为字符串数组?
这是我目前的尝试,但正如你所看到的,它没有过滤掉前面的-(破折号),在每个单词后面包含一个空字符,并将“自动驾驶汽车”分成两个不同的元素。
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"]这是我想要的正确结果
["AI", "Tools", "Food", "Safety", "Objects", "High Shelves", "Monitoring", "Movement", "Lawns", "Windows", "Bathing", "Hygiene", "Repetitive", "Physical", "Self-Driving Cars", "Smartphones", "Chatbots"]发布于 2022-07-25 07:53:34
你可以总是map,trim和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));
发布于 2022-07-25 08:16:41
我能够使用以下方法解决这个问题:
// 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);发布于 2022-07-25 08:22:11
您可以尝试使用下一个正则表达式:(\r_\\n)--为了从开始或结束消除空元素,可以在使其数组之前使用.trim()。( console.log(keywords.split(/(\r|\n)-/).trim().filter((element) =>元素))
https://stackoverflow.com/questions/73105632
复制相似问题