简体   繁体   English

如何根据javascript中的多个分隔符将字符串拆分为多个数组

[英]How to split a string to multiple arrays based on multiple separators in javascript

I have seen the questions but none of them helped me.我已经看到了这些问题,但没有一个对我有帮助。 I have a string like this:我有一个这样的字符串:

var Lang_Array1 = "HU,blah,blah,blah,EN,blah,blah,blah,blah,DE,blah,blah,blah,RO,blah,blah,blah"; var Lang_Array1 = "HU,blah,blah,blah,EN,blah,blah,blah,blah,DE,blah,blah,blah,RO,blah,blah,blah";

I want that string to be in different arrays based on the separators "HU", "EN", "DE", "RO" .我希望该字符串基于分隔符"HU", "EN", "DE", "RO"位于不同的数组中。

My approach currently is this ( Working but not too elegant ):我目前的方法是这样的工作但不太优雅):

var Lang_Array1 = Lang_Array.split(",");
    console.log(typeof(Lang_Array));
    console.log(Lang_Array);

    var HU_Langs = [];
    var EN_Langs = [];
    var DE_Langs = [];
    var RO_Langs = [];

    for(var i = 0; i < Lang_Array1.length;i++){
        if(Lang_Array1[i] != "EN"){
            if(Lang_Array1[i] != ""){
                HU_Langs[i] = Lang_Array1[i];
            }
        }else{
            for(i;i < Lang_Array1.length;i++){
                if(Lang_Array1[i] != "DE"){
                    if(Lang_Array1[i] != ""){
                        EN_Langs[i] = Lang_Array1[i];
                    }
                }else{
                    for(i;i < Lang_Array1.length;i++){
                        if(Lang_Array1[i] != "RO"){
                            if(Lang_Array1[i] != ""){
                                DE_Langs[i] = Lang_Array1[i];
                            }
                        }else{
                            for(i;i < Lang_Array1.length;i++){
                                    if(Lang_Array1[i] != ""){
                                        RO_Langs[i] = Lang_Array1[i];
                                    }       
                                }
                            break;
                        }
                    }
                    break;
                }
            }
            break;
        }
    }

That way i get what i want but i want to improve it somehow.这样我得到了我想要的,但我想以某种方式改进它。 The arrays:数组:

HU_Langs =["HU","blah","blah","blah"];
EN_Langs =["EN","blah","blah","blah"];
DE_Langs =["DE","blah","blah","blah"];

etc...等等...

So how can i improve this code without nested for loops?那么如何在没有嵌套 for 循环的情况下改进此代码?

EDIT: Thank you for all!编辑:谢谢大家! All the answers are very very good.所有的答案都非常非常好。 My question wasnt clear and detailed enough but i solved it like this with the help of the correct answer.我的问题不够清楚和详细,但我在正确答案的帮助下解决了这个问题。

Here is the function now:这是现在的功能:

function Get_Language_Object(Lang_Array){
    Lang_Array = Lang_Array.replace(/(\r\n|\n|\r)/gm, "");
    var langs = ['HU', 'EN', 'DE', 'RO'];
    var isLang = str => langs.includes(str);
    var { HU: New_HU_Langs, EN: New_EN_Langs, DE: New_DE_Langs, RO: New_RO_Langs } = Lang_Array.split(',')
        .reduce((r, str) => {
    if(isLang(str)) r.push([]);
        r[r.length - 1].push(str);
        return r;
    }, [])
        .reduce((r, [code, ...arr]) => ({ ...r, [code]: arr }), {});
    for(var i = 0; i < TAGS.length;i++){
        arrLang.HU[TAGS[i]] = New_HU_Langs[i];
        arrLang.EN[TAGS[i]] = New_EN_Langs[i];
        arrLang.DE[TAGS[i]] = New_DE_Langs[i];
        arrLang.RO[TAGS[i]] = New_RO_Langs[i];
    }
    Set_Actual_Language();
    VNotify("Settings Notfy","Lang Set!","success",1500,"success32.png");
}

Split the string by the delimiter ( , ), reduce the array, and for every language code, add a new sub-array.通过分隔符 ( , ) 拆分字符串,减少数组,并为每个语言代码添加一个新的子数组。 Push all items to the last sub-array:将所有项目推送到最后一个子数组:

 var Lang_Array1 = "HU,blah,blah,blah,EN,blah,blah,blah,blah,DE,blah,blah,blah,RO,blah,blah,blah"; var langs = ['HU', 'EN', 'DE', 'RO']; var isLang = str => langs.includes(str); var result = Lang_Array1.split(',') .reduce((r, str) => { if(isLang(str)) r.push([]); r[r.length - 1].push(str); return r; }, []); console.log(result);

If you want to split to multiple arrays, reduce the sub-arrays to an object, and use desturcturing to assign them to variables:如果要拆分为多个数组,则将子数组缩减为一个对象,并使用解构将它们分配给变量:

 var Lang_Array1 = "HU,blah,blah,blah,EN,blah,blah,blah,blah,DE,blah,blah,blah,RO,blah,blah,blah"; var langs = ['HU', 'EN', 'DE', 'RO']; var isLang = str => langs.includes(str); var { HU: HU_Langs, EN: EN_Langs, DE: DE_langs, RO: RO_langs } = Lang_Array1.split(',') .reduce((r, str) => { if(isLang(str)) r.push([]); r[r.length - 1].push(str); return r; }, []) .reduce((r, [code, ...arr]) => ({ ...r, [code]: arr }), {}); console.log(HU_Langs, EN_Langs, DE_langs, RO_langs);

You should reduce the list of words after splitting on your delimiter ( , ).在分隔符 ( , ) 上拆分后,您应该减少单词列表。 Each time you run into a known key, you alter the key that refers to the current language.每次遇到已知键时,都会更改引用当前语言的key

This is the most succinct example:这是最简洁的例子:

 let arr = "HU,blaf,blaf,blaf,EN,blah,blah,blah,blah,DE,bla,bla,bla,RO,bah,bah,bah" let keys = [ "DE", "EN", "HU", "RO" ] let dict = langDict(arr, keys) console.log(dict) function langDict(arr, keys) { let key = null return arr.split(/,/g).reduce((dict, token) => { if (Object.keys(dict).length && key == null) { throw new Error('No language defined yet!') } else if (keys.includes(token)) { key = token } else { if (dict[key] == null) dict[key] = [] dict[key].push(token) } return dict }, {}) }
 .as-console-wrapper { top: 0; max-height: 100% !important; }

As I believe the upper case ISO2 code is the language hint, you could group all results together in a more scalable way.因为我相信大写的 ISO2 代码是语言提示,所以您可以以更具可扩展性的方式将所有结果组合在一起。

var Lang_Array1 = "HU,blah,blah,blah,EN,blah,blah,blah,blah,DE,blah,blah,blah,RO,blah,blah,blah";
var Languages = {};
var current = '';

Lang_Array1.split(',').forEach(function (value) {
  if (/^[A-Z]{2}$/.test(value))
    current = value;
  else
    Languages[current] = (Languages[current] || []).concat(value);
});

console.log(Languages);

Above snippet would populate the Languages object like this:上面的代码片段会像这样填充Languages对象:

{
  "HU": [
    "blah",
    "blah",
    "blah"
  ],
  "EN": [
    "blah",
    "blah",
    "blah",
    "blah"
  ],
  "DE": [
    "blah",
    "blah",
    "blah"
  ],
  "RO": [
    "blah",
    "blah",
    "blah"
  ]
}

At this point, all you have to do is to address directly Languages.EN or others, or recreate the original structure via:此时,您所要做的就是直接寻址Languages.EN或其他,或者通过以下方式重新创建原始结构:

var Lang_Array = Object.keys(Languages).reduce(
  function (arr, key) {
    return arr.concat(key, Languages[key]);
  },
  []
);

You could also create arrays with the language starting at index 0, and values following:您还可以使用从索引 0 开始的语言和以下值创建数组:

var Lang_EN = ['EN'].concat(Languages.EN);

As summary, grouping by keys seem the best way to represent, and manipulate, such flattened structure.总之,按键分组似乎是表示和操作这种扁平结构的最佳方式。

I hope this helped 👋我希望这有帮助👋

If the order is constant:如果顺序不变:

var Lang_Array1 = "HU,blah1,blah2,blah3,EN,blah4,blah5,blah6,blah7,DE,blah8,blah9,blah10,RO,blah11,blah12,blah13";
const arr1 = Lang_Array1.split(/[HU,EN,DE,RO]/g);
let obj = {hu:[],en:[],de:[],ro:[]};
const keys = Object.keys(obj);
let i = 0;
arr1.forEach(el=>{
    if(el !== '')
      obj[ keys[i] ].push(el);
  else
    if(obj[ keys[i] ].length > 0)
      i++;
 });

console.log(obj);

Response:回复:

{hu: Array(3), en: Array(4), de: Array(3), ro: Array(3)}
hu: (3) ["blah1", "blah2", "blah3"]
en: (4) ["blah4", "blah5", "blah6", "blah7"]
de: (3) ["blah8", "blah9", "blah10"]
ro: (3) ["blah11", "blah12", "blah13"]

Temporary array can be used to reference the array to push to :临时数组可用于引用要推送到的数组:

 var Lang_Array = "HU,blah,blah,blah,EN,blah,blah,blah,blah,DE,blah,blah,blah,RO,blah,blah,blah"; var Lang_Array1 = Lang_Array.split(","), HU_Langs = [], EN_Langs = [], DE_Langs = [], RO_Langs = []; for (var Langs = [], i = 0; i < Lang_Array1.length; i++) { var str = Lang_Array1[i]; Langs = { HU: HU_Langs, EN: EN_Langs, DE: DE_Langs, RO: RO_Langs }[str] || Langs; Langs.push(str); } console.log( HU_Langs, EN_Langs, DE_Langs, RO_Langs );

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

相关问题 拆分多个分隔符的字符串 - Split string with multiple separators 用多个分隔符分割字符串 - String split with multiple separators 用多个分隔符在javascript中拆分字符串并保留它们 - Split a string in javascript with multiple separators and keep them 如何在 JavaScript 中拆分具有多个分隔符的字符串? - How do I split a string with multiple separators in JavaScript? javascript:为多个分隔符拆分字符串,但也将分隔符保留为单独的标记 - javascript: split string for multiple separators but also keep the separators as separate token 如何在JavaScript中使用多个分隔符分隔字符串? - How do I split a string with multiple separators acting only as one in javascript? 如何在不使用正则表达式的情况下在 javascript 中拆分具有多个分隔符的字符串? - How do I split a string with multiple separators in javascript without using regexp? 如何在 JavaScript 中使用多个分隔符拆分网站 URL? - How do I split a website URL with multiple separators in JavaScript? 使用多个分隔符拆分字符串并将分隔符保留在结果中 - Split string using multiple separators and keep the separators in the result javascript 如何在特定字符后将字符串拆分为多个 arrays - javascript how to split a string in multiple arrays after specific character
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM