1

I have the following code:

var s=Stop;5,Service;13,Error;21,LINK DOWN;53,Data Incomplete;2,Replication Off;0,LINK DOWN;53

I need to loop in and get:

stop 5
Service 13
Error 21
.
.

I need to use an array because I have to get the value of stop service to show it on my html.

I have tried this:

var rslt = [];
for (var i = 0; i < 5; i++) {
  rslt[i] = s.substr(i, s.indexOf(','));
}

But it does not give me what I want.

Scath
  • 3,777
  • 10
  • 29
  • 40
  • First, your `s` string is not properly declared. You need to put the value in between quotes `var s = "Stop;5;"` ... – Guillaume Georges May 16 '18 at 14:10
  • Your `s` declaration is not valid syntax. Is `s` a String? Use quotes `"`. – zero298 May 16 '18 at 14:10
  • its result of an ajax call –  May 16 '18 at 14:11
  • Use the answer(s) to [this question](https://stackoverflow.com/q/901115/215552), just replace `&` with `,` and `=` with `;`. – Heretic Monkey May 16 '18 at 14:12
  • Possible duplicate of [How to split comma and semicolon separated string into a two dimensional array](https://stackoverflow.com/questions/37334141/how-to-split-comma-and-semicolon-separated-string-into-a-two-dimensional-array) – Heretic Monkey May 16 '18 at 14:14

4 Answers4

0

Simply use split method with , as the argument. You don't need any loop for this.

const arr = 'Stop;5,Service;13,Error;21,LINK DOWN;53,Data Incomplete;2,Replication Off;0,LINK DOWN;53'.split(',');
console.log(arr);

And if you want to get rid of those semicolons as well then you can do this.

const arr = 'Stop;5,Service;13,Error;21,LINK DOWN;53,Data Incomplete;2,Replication Off;0,LINK DOWN;53'
  .split(',')
  .map(item => item.replace(';', ' '));
  
console.log(arr);
Matus Dubrava
  • 13,637
  • 2
  • 38
  • 54
0

You could split by comma and map the splitted values with semicolon.

var s = 'Stop;5,Service;13,Error;21,LINK DOWN;53,Data Incomplete;2,Replication Off;0,LINK DOWN;53',
    values = s.split(',').map(t => t.split(';'));

console.log(values);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Simply replace the ; by a space. Then split your string into an array as following :

var temp = s.replace(";", " ").split(",");

NB : Your variable s is not well declared. Perhaps have I misunderstood the format of your "text".

Gilles-Antoine Nys
  • 1,481
  • 16
  • 21
-1

Try with replace() and split():

var s='Stop;5,Service;13,Error;21,LINK DOWN;53,Data Incomplete;2,Replication Off;0,LINK DOWN;53'

s = s.replace(/;/g,' ').split(',');
console.log(s);

OR: If you want make with nested array:

var s='Stop;5,Service;13,Error;21,LINK DOWN;53,Data Incomplete;2,Replication Off;0,LINK DOWN;53'

s = s.replace(/;/g,' ').split(',').map(i=> i.split(' '));
console.log(s);
Mamun
  • 66,969
  • 9
  • 47
  • 59