我试图将所有数据合并成多行,直到遇到分号(;)为止。
输入
1
09;
8
9;
10
9;
1
00
;
2
0;输出
109
89
109
100
20如何使用JavaScript?实现这一点?
这些数据不是静态的,而是动态的,数据是实时的,我需要处理一个数据值,直到分号,然后使用套接字将它推到浏览器前端。因此,我不需要一次处理所有数据,然后推送它。
这样做:
console.log("before: ",receivedData);
console.log("after: ",receivedData.split('\n').join('').split(';').join('\n'));在以下方面的成果:
after:
before: 2
after: 2
before: 05
after: 05
before: ;
after:
before:
after:
before: 2
after: 2
before: 12
after: 12
before: ;
after:每半秒钟(500毫秒)就会有新的数据。我不知道它是否太快,不能处理?我想这只是实时的,所以没有时间计算?
发布于 2017-07-29 11:19:01
您要寻找的代码可能是这样的:
var buffer = '';
function process(data){
var separatorIndex;
while((separatorIndex = data.indexOf(';')) !== -1){
send(buffer + data.substr(0, separatorIndex));
buffer = '';
data = data.substr(separatorIndex + 1);
}
buffer += data;
}
function send(data){
console.log(data);
}
process('123');
process('456;789;123');
process(';');
如果您能够同时积累所有数据并对其进行转换,test.replace(/[^0-9;]|;$/g, '').replace(/;/g, '\r\n')就应该做到这一点。第一个regexp移除所有不是数字或分号的东西(万一后面是分号),第二个调用用换行符替换所有分号。
发布于 2017-07-29 11:40:03
添加一个表示数据的字符串。记住在每一行末尾转义(使用反斜杠)使其在上面运行(或者,使用字符串模板,正如我在下面所做的那样:)
const data =`
1
09;
8
9;
10
9;
1
00
;
2
0;`
const target = []; //Where our results will end up.然后,对数据使用for循环:
var current = 0;
for (var iterator = 0; iterator > data.length; iterator++) {
if (!target[current]) {target[current] = '';}
if (data[iterator] != ";" && data[iterator] != "\n") {
target[current] += data[iterator]; //Add current data to the target
continue; //Continue the loop.
}
else if (data[iterator] == ";") {
current++; //Add one to current, so that further text ends up in the next index
continue; //Continue the loop.
}
else {
continue;
}
}当然,这是无效的,但它会起作用,如果您是新的JS,您将沿着这条路线走下去。字符串操作是一项具有不同难度的任务。您还可以使用正则表达式或.join和.split链来实现与此循环相同的功能。
发布于 2017-07-29 11:56:45
删除所有空白,然后在;上拆分
var str =`1
09;
8
9;
10
9;
1
00
;
2
0;`
var res = str.replace(/\s/g, '').split(';').join('\n')
console.log(res)
https://stackoverflow.com/questions/45388595
复制相似问题