Abdul Manaf
Abdul Manaf

Reputation: 4993

Split string on 2nd occurrence of characters JavaScript

I want to split a string using a comma and need to populate an array of JSON. I have the following string data

const test='00000001,name1,00000002,name2,00000003,name3,00000004,name4';

console.log(test.split('/[\n,|]/',2));

Output : ['00000001','name1','00000002','name2','00000003','name3','00000004','name4']

But I need output like this

[{id:'00000001',name:'name1'},{id:'00000002',name:'name2'},{id:'00000003',name:'name3'},{id:'00000004',name:'name4'}]

Upvotes: 0

Views: 678

Answers (4)

The fourth bird
The fourth bird

Reputation: 163217

Another way could be using a pattern with named capture groups.

For capturing digits for the id, matching the comma and capture word characters for the name:

(?<id>\d+),(?<name>\w+)

const test = '00000001,name1,00000002,name2,00000003,name3,00000004,name4';
const result = Array.from(
  test.matchAll(/(?<id>\d+),(?<name>\w+)/g),
  m => m.groups
);
console.log(result);

If you want to capture all characters for the id and name except for a comma or whitespace char you can use a negated character class [^,\s]+

(?<id>[^,\s]+),(?<name>[^,\s]+)

const test = '00000001,name1,00000002,name2,00000003,name3,00000004,name4';
const result = Array.from(
  test.matchAll(/(?<id>[^,\s]+),(?<name>[^,\s]+)/g),
  m => m.groups
);
console.log(result);

Upvotes: 0

DecPK
DecPK

Reputation: 25408

You can easily achieve this result by first match the strings with /(\d)+,(\w)+/gi. It will give you an array of strings.

Then you can use the map to get the desired result.

const test = "00000001,name1,00000002,name2,00000003,name3,00000004,name4";

const regex = /(\d)+,(\w)+/gi;
const result = test.match(regex).map((str) => {
  const [id, name] = str.split(",");
  return { id, name };
});

console.log(result);

Upvotes: 3

Darshil Dave
Darshil Dave

Reputation: 111

Assuming the array is of even length, this output can be achieved by doing :

const test='00000001,name1,00000002,name2,00000003,name3,00000004,name4';
let words = test.split(",");
let output = [];
let obj = {};
for (let i = 0; i < words.length; i++) {
  if (i % 2 == 0) {
  obj = {};
  obj["id"] = words[i];
  }
  
  else {
  obj["name"] = words[i];
  output.push(obj);
  }
}
console.log(output);

Upvotes: 0

s_frix
s_frix

Reputation: 323

you can use Map function to cast your couple key value

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map?retiredLocale=it

Upvotes: 0

Related Questions