[英]Loop through a text with semicolon and comma using javascript
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. 我需要使用一个数组,因为我必须获取stop服务的值才能在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. 但这并没有给我我想要的东西。
Simply use split
method with ,
as the argument. 只需使用
split
与方法,
作为参数。 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);
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; }
Try with replace()
and split()
: 尝试使用
replace()
和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);
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. 注意:您的变量s声明不正确。 Perhaps have I misunderstood the format of your "text".
也许我误解了您“文本”的格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.