Skip to content
Advertisement

How to split the text by every second specified character?

For example, i have this string:

1:55520:2:THE LIGHTNING ROAD:5:3:6:28762:8:10:9:10:10:44654418:12:3:13:21:14:2440639:17:1:43:3:25::18:10:19:12:42:0:45:3527:3:UmVtb3ZlZCBDb2lucywgfiBUaW1lbGVzcyBSZWFsIC8gUmVkdWxvYw==:15:3:30:55520:31:0:37:0:38:0:39:10:46:1:47:2:35:0#28762:timeless real:6805706##9999:0:10#9c3be04b52b77197134e199989920f4aa55b933b

And I want to split everything in it by every second colon (:). How can I do it?

Required Output

[
  "1:55520",
  "2:THE LIGHTNING ROAD",
  "5:3",
  "6:28762",
  "8:10",
  "9:10",
  "10:44654418",
  "12:3",
  "13:21",
  "14:2440639",
  "17:1",
  "43:3",
  "25:",
  "18:10",
  "19:12",
  "42:0",
  "45:3527",
  "3:UmVtb3ZlZCBDb2lucywgfiBUaW1lbGVzcyBSZWFsIC8gUmVkdWxvYw==",
  "15:3",
  "30:55520",
  "31:0",
  "37:0",
  "38:0",
  "39:10",
  "46:1",
  "47:2",
  "35:0#28762",
  "timeless real:6805706##9999",
  "0:10#9c3be04b52b77197134e199989920f4aa55b933b"
]

Advertisement

Answer

Sure. You just have to use in-built function .split( ). Here if you have str = "Hi there Go" then on str.split(‘ ‘)you will get[‘Hi’,’there’,’Go’]` You can do the same in your case.

let str ="1:55520:2:THE LIGHTNING ROAD:5:3:6:28762:8:10:9:10:10:44654418:12:3:13:21:14:2440639:17:1:43:3:25::18:10:19:12:42:0:45:3527:3:UmVtb3ZlZCBDb2lucywgfiBUaW1lbGVzcyBSZWFsIC8gUmVkdWxvYw==:15:3:30:55520:31:0:37:0:38:0:39:10:46:1:47:2:35:0#28762:timeless real:6805706##9999:0:10#9c3be04b52b77197134e199989920f4aa55b933b";

let elem = str.split(':');
let arr = [];
for(let i =0;i<elem.length;i++)
{
  if(i%2!=0)
  {
    arr.push(elem[i-1]+`:`+elem[i]);
  }
}

console.log(arr)
Advertisement