简体   繁体   中英

javascript split( /\r\n|\n|\r/) with semicolon

I use the following code in javascript

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

to split the result which appears like:

x = 1;

y = 3;

z = 4;

into an array tmp, but i get the semicolon(;) as well

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

what I need is

[ "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. 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.

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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