+ 1

how can i separate a string with spaces in an array?

I have an array for example: "01/06/2021 12-0020092 10.00", with different spaces, and what I want to do is separate it into an array with the respective values but not including the spaces, if I use split(" "), it returns me a fairly large array since it includes all the spaces, and I can't be very specific with the spaces because these can vary. How could I separate the string into an array without including the spaces?.

18th Jul 2021, 6:56 PM
Sam Vásquez
Sam Vásquez - avatar
9 odpowiedzi
+ 1
Maybe this helps? var s = " a b c ".trim(); s = s.replace(/\s+/g, ' '); console.log(s); It removes "unnecessary" whitespace characters but leaves enough for splitting.
18th Jul 2021, 7:09 PM
Lisa
Lisa - avatar
+ 1
You can use the array method filter let test = "01/06/2021 12-0020092 10.00"; console.log(test.split(' ').filter(a=>a)) // ["01/06/2021", "12-0020092", "10.00"]
18th Jul 2021, 7:43 PM
ODLNT
ODLNT - avatar
+ 1
oh ok, gracias a todos por la ayuda 👌
18th Jul 2021, 7:46 PM
Sam Vásquez
Sam Vásquez - avatar
0
Use regular expression (regex) const str = "01 / 06 / 2021"; const stringArray = str.split(/(\s+)/); console.log(stringArray); // ["01", " ", "06", " ", "2021"] \s matches any character that is a whitespace. https://code.sololearn.com/cB6AQHG6rb18/?ref=app
18th Jul 2021, 7:15 PM
Matias
Matias - avatar
0
Lisa Yes of course, I would use to join the string by removing / replacing the spaces, but it joins them, and what I look for is to separate the elements in an array without including the spaces
18th Jul 2021, 7:24 PM
Sam Vásquez
Sam Vásquez - avatar
0
1. trim() 2. replace() 3. split() ?
18th Jul 2021, 7:34 PM
Lisa
Lisa - avatar
0
But how can I use split if the string is joined? By what character or symbol could I separate it?
18th Jul 2021, 7:39 PM
Sam Vásquez
Sam Vásquez - avatar
0
Sam Vásquez How about using regex to remove all the spaces either between two spaces or between a space and a character and then splitting the string? A faster way would be to use dynamic programming.
20th Jul 2021, 2:31 PM
Calvin Thomas
Calvin Thomas - avatar