简体   繁体   English

根据特殊字符和换行符将字符串拆分为多个字段 - Javascript

[英]Split strings into multiple fields based on special characters and newline - Javascript

I have a profile field where the data comes in the below format for each user profile.我有一个配置文件字段,其中每个用户配置文件的数据格式如下。

User1 could have his profile field populated as below while user2 could have just one role/id/company listed in their profile.用户 1 可以按如下方式填充他的个人资料字段,而用户 2 可以在他们的个人资料中仅列出一个角色/id/公司。

RoleA : 123456 - company1 \n

RoleB : 234567 - company2 \n

RoleC : 891011

I am supposed to split the roles for each user into 1 field separated by commas and the id/company into another field separated by comma.我应该将每个用户的角色拆分为用逗号分隔的 1 个字段,将 id/company 拆分为另一个用逗号分隔的字段。

For the above data, the output should look like-对于上述数据,output 应该看起来像 -

Role field - RoleA, RoleB, RoleC

ID/Company field - 123456-company1, 234567-company2.

This has to be done in JavaScript .这必须在JavaScript中完成。 Any suggestion is appreciated.任何建议表示赞赏。

Thanks!谢谢!

What you should do is something similar to below:你应该做的是类似于下面的事情:

function splitProfile(profile, roleList, idCompanyList) {
  var splitProfileString = profile.split(" : ");
  roleList.push(splitProfileString[0]);

  var splitIdCompanyString = splitProfileString[1].split(" - ");
  // check if there is a company for `id`
  if(splitIdCompanyString[1]) {
    idCompanyList.push(splitIdCompanyString[0] + "-" + splitIdCompanyString[1].replace(" \n", ""));
  }
}


var roleIdCompanyList = [
  "RoleA : 123456 - company1 \n",
  "RoleB : 234567 - company2 \n",
  "RoleC : 891011"
];

var roleList = [];
var idCompanyList = [];

roleIdCompanyList.forEach(function(roleIdCompany) {
  splitProfile(roleIdCompany, roleList, idCompanyList);
});

console.log(roleList.join(", ")); // RoleA, RoleB, RoleC
console.log(idCompanyList.join(", ")); // 123456-company1, 234567-company2

I tried to think that the input and the output are exactly similar to the ones you provided in the question.我试图认为输入和 output 与您在问题中提供的完全相似。 In any case, I hope you get the idea of what I am trying to do here.无论如何,我希望你能明白我在这里想要做什么。

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

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