Ruthock
Ruthock

Reputation: 39

Convert string to array, that has a lot of white spaces

So, I have a string similar to this:

The text editor removes all the white spaces, however there are maybe 15-20 white spaces on every new line before the first names

 Jake Senior
                             Stephen Abert
                             Benny Andrnw
                             Jacob Ben Juniour
                             Michael Smith

However I'm having trouble in splitting it into an array, as splitting by white spaces creates several emtpy values in the array, I'm also trying to get the both names each time rather than split them in seperate values

Upvotes: 1

Views: 491

Answers (3)

phuzi
phuzi

Reputation: 13060

Without knowing exactly what the line endings are you should probably do something like this:

let input = `Jake Senior
                             Stephen Abert
                             Benny Andrnw
                             Jacob Ben Juniour
                             Michael Smith`;
let result = input.split('\n').map((s) => s.trim());

console.log(result);

Upvotes: 0

Richard
Richard

Reputation: 7433

Split the string by newline (\n), then use trim() to remove whitespaces in the front and back of the string.

let string = `Jake Senior
                             Stephen Abert
                             Benny Andrnw
                             Jacob Ben Juniour
                             Michael Smith`
                             
let processedString = string.split('\n').map(elem => elem.trim())
console.log(processedString)

Upvotes: 7

Rajesh
Rajesh

Reputation: 24915

You can use regex to define the pattern (\s{2,}). This would mean split string when there are 2 or more spaces.

You will also have to process split value as they can have trailing spaces around them.

var str = ' Jake Senior\
                             Stephen Abert\
                             Benny Andrnw\
                             Jacob Ben Juniour\
                             Michael Smith';
                             
console.log(str.split(/\s{2,}/).map(name => name.trim()));

Upvotes: 0

Related Questions