如何使用拆分根据条件分隔字符串?

时间:2021-03-26 18:34:29

标签: javascript

早上好,我有这些文本字符串:

json_schema.account_overview.name
json_schema.no_owned.contact.contact

但现在我试图根据字符串 'json_schema.no_owned' 分开,这样做:

my_string.split ("json_schema.no_owned."). filter (x => x);

但是我得到这个结果的 console.log

enter image description here

第一个排列很好,因为对于相同的排列,我可以应用另一个拆分,并且我将再次以“。”分隔。 但是第二个修复与我所说的应该在“json_schema.no_owned”之后无关。 (注意末尾的句号)

我正在尝试这样做:

let string ="json_schema.no_owned.contact.contact";
let arrayString = [
  'json_schema.no_owned.contact.contact',
  'json_schema.account_overview.name'
];

let schema = "";
for(let i in arrayString){
   schema = arrayString[i].split("json_schema.no_owned.").filter(x => x);
console.log(schema);   
}

我只想在数组中包含 'json_schema.no_owned' 之后的元素 谢谢。

2 个答案:

答案 0 :(得分:1)

您可以检查元素是否具有“json_schema.no_owned”。部分:

let string ="json_schema.no_owned.contact.contact";
let arrayString = [
  'json_schema.no_owned.contact.contact',
  'json_schema.account_overview.name'
];

let schema = "";
for(let i in arrayString){
   if (arrayString[i].includes("json_schema.no_owned.")) {
      schema = arrayString[i].split("json_schema.no_owned.").filter(x => x);
      console.log(schema);  
   }
}

答案 1 :(得分:0)

也许你可以用一个简短的方法来做到这一点。

let arrayString = [
  'json_schema.no_owned.contact.contact',
  'json_schema.account_overview.name'
];

const schemas = arrayString.filter(x => x.includes("json_schema.no_owned."))
                           .map(x => x.split("json_schema.no_owned.")[1]);
相关问题