Borislav Hadzhiev
Tue Nov 16 2021·2 min read
Photo by Sergey Sokolov
To split a string and trim the surrounding spaces:
split()
method on the string.map()
method to iterate over the array.trim()
method on the string to remove the
surrounding spaces.const str = 'one - two - three'; const result = str.split('-').map(element => element.trim()); console.log(result); // 👉️ ['one', 'two', 'three']
The first step is to use the String.split method to split the string into an array.
The only parameter we passed to the split
method is the separator by which we
want to split the string.
const str = 'one - two - three'; // 👇️ ['one', 'two', 'three'] console.log(str.split('-'));
The function we passed to the Array.map method gets called with each element (substring) in the array.
On each iteration, we use the String.trim method to remove the leading and trailing spaces from the string.
// 👇️ "abc" console.log(' abc '.trim());
The map
method returns a new array that contains the values we returned from
the callback function.
2
of the same separators next to one another.In the scenario that there are multiple separator characters next to one another, we'd get a bunch of empty strings.
// 👇️ ['one', '', ' two ', '', ' three'] console.log('one -- two -- three'.split('-'));
We're splitting on each hyphen, but have two hyphens next to one another, so we get an empty string for the second hyphen.
To handle this scenario, we can use the Array.filter method to filter out any empty strings from the array.
const str = ' one -- two -- three '; const result = str .split('-') .map(element => element.trim()) .filter(element => element !== ''); console.log(result); // 👉️ ['one', 'two', 'three']
The function we passed to the filter()
method gets called for each element of
the array.
On each iteration, we check if the element is not equal to an empty string.
The filter
method returns a new array that contains only the values that
satisfy the condition.