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'...]
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.
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.
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.
Thank you for comments. It seems that quotes are not needed at all:
> out.split(/\s+/);
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()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With