输入字符串:“ abc def,ghi jkl,mnopq”
所需的输出数组: [“ abc”,“ def”] [“ ghi”,“ jkl”] [“ mnopq”]
输入可以是用空格分隔的短语的任意组合,然后用逗号分隔这些短语。我需要为每个输入字符串创建一个新数组,然后跟一个逗号。创建这些数组时,必须用“”将它们分隔。
以下是使用逗号作为分隔符将字符串拆分为数组值的代码:
str = "abc def, ghi jkl, mnopq";
const commaSeparatedArray = this.str.split(',').filter(s => s.slice(-1) !== ' ');
console.log(commaSeparatedArray);
不确定在此采取的下一步是进行此类操作还是javascript原型的for或while循环?
链接到stackblitz: https://stackblitz.com/edit/angular-ivy-vbdae5?file=src%2Fapp%2Fapp.component.ts
答案 0 :(得分:5)
以下内容为您提供了一个数组数组。如果您正在寻找类似的东西。
var s = "abc def, ghi jkl, mnopq";
var result = s.split(',').map(a=>a.trim().split(' '));
console.log(result);
答案 1 :(得分:2)
str = "abc def, ghi jkl, mnopq";
//you need to again split and filter out the empty string to get the desired output.
const commaSeparatedArray = this.str.split(',').map(item => {
const d = item.split(' ').filter(i => i);
return [...d]
})
console.log(commaSeparatedArray)
答案 2 :(得分:1)
您基本上只想进行两轮拆分
const str = "abc def, ghi jkl, mnopq";
const result = str.split(/,\s*/).map(substr => substr.split(/\s+/))
console.info(result)
那是
答案 3 :(得分:1)
const str = "abc def, ghi jkl, mnopq";
const commaSeparatedArray = str.split(",");
const result = commaSeparatedArray.reduce((acc, stringWithspaces) => {
return [...acc, stringWithspaces.split(" ").filter(string=> string)];
}, []);
console.log(result);
答案 4 :(得分:1)
希望我能对您有所帮助
var str = "abc def, ghi jkl, mnopq";
var res = str.split(', ').map(x => x.split(' '));
console.log(res);