Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String By Multiple Spaces NodeJS

I have this in node:

>out
'java    1303 root  187u   CHR  166,0      0t0 14586 /dev/ttyACM0\n'
>typeof out
'string'
> out.split("\\s+"); 
[ 'java    1303 root  187u   CHR  166,0      0t0 14586 /dev/ttyACM0\n' ]

I would expect the splitted string, e.g. ['java','1303','root'...]

like image 704
gdm Avatar asked Oct 27 '16 10:10

gdm


People also ask

How do you split a string by multiple delimiters?

To split a string with multiple delimiters:Use the str. replace() method to replace the first delimiter with the second. Use the str. split() method to split the string by the second delimiter.

How do I split a string with multiple separators in typescript?

String split() Method: The str. split() function is used to split the given string into array of strings by separating it into substrings using a specified separator provided in the argument.

How do you split a string in white space?

You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.


2 Answers

Thank you for comments. It seems that quotes are not needed at all:

> out.split(/\s+/); 
like image 120
gdm Avatar answered Nov 01 '22 10:11

gdm


You split with a literal string \s+, it would split "a\\s+b" into a and b.

Use a regex, RegExp("\\s+") or /\s+/ (better, since the pattern is static):

var s = 'java    1303 root  187u   CHR  166,0      0t0 14586 /dev/ttyACM0\n';
console.log(s.trim().split(/\s+/));

I also suggest trimming the input to get rid of empty elements at the start/end.

Also note that .split(/\s+/g) = .split(/\s+/) (the global modifier is implied with String#split()).

like image 9
Wiktor Stribiżew Avatar answered Nov 01 '22 11:11

Wiktor Stribiżew