+ 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?.
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.
+ 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"]
+ 1
oh ok, gracias a todos por la ayuda 👌
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
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
0
1. trim()
2. replace()
3. split()
?
0
But how can I use split if the string is joined? By what character or symbol could I separate it?
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.