简体   繁体   English

javascript使用分号(/ \\ r \\ n | \\ n | \\ r /)

[英]javascript split( /\r\n|\n|\r/) with semicolon

I use the following code in javascript 我在javascript中使用以下代码

console.log(result);
tmp = result.split(/\r\n|\n|\r/);
console.log(tmp);

to split the result which appears like: 拆分结果如下所示:

x = 1; x = 1;

y = 3; y = 3;

z = 4; z = 4;

into an array tmp, but i get the semicolon(;) as well 到一个数组的tmp,但我也得到了分号(;)

[ "x = 1;", "y = 3;", "z = 95;"] [“ x = 1;”,“ y = 3;”,“ z = 95;”]

what I need is 我需要的是

[ "x = 1", "y = 3", "z = 95"] [“ x = 1”,“ y = 3”,“ z = 95”]

without the semicolon, what should I add? 没有分号,我应该添加什么?

I suppose you mean semicolon and not question mark. 我想你的意思是分号而不是问号。 Anyway as the parameter inside the split function is a regex you can change it to match also the semicolon. 无论如何,由于split函数中的参数是一个正则表达式,您可以对其进行更改以匹配分号。 If you are sure the semicolon will be there just use this: 如果您确定分号在那里,请使用以下命令:

tmp = result.split(/;\r\n|;\n|;\r/);

If you are not sure the semicolon is always there just use this one: 如果不确定分号是否总是存在,请使用以下命令:

tmp = result.split(/;?\r\n|;?\n|;?\r/);

The ? in the last regex mean '0 or 1' so it check if the semicolon is there and if it is it use it as separator. 在最后一个正则表达式中表示“ 0或1”,因此它检查分号是否存在以及是否使用分号作为分隔符。

You can just replace them with nothing before doing the splitting: 您可以在拆分之前将它们替换为空:

 result = `x = 1; y = 3; z = 4;` console.log(result); tmp = result.replace(/;/g, "").split(/\\r\\n|\\n|\\r/); console.log(tmp); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM