Split String and Trim surrounding Spaces in JavaScript

avatar

Borislav Hadzhiev

Tue Nov 16 20212 min read

Split String and Trim surrounding Spaces #

To split a string and trim the surrounding spaces:

  1. Call the split() method on the string.
  2. Call the map() method to iterate over the array.
  3. On each iteration, call the trim() method on the string to remove the surrounding spaces.
index.js
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.

index.js
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.

index.js
// ๐Ÿ‘‡๏ธ "abc" console.log(' abc '.trim());

The map method returns a new array that contains the values we returned from the callback function.

There is an edge case that you might need to handle - there might be 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.

index.js
// ๐Ÿ‘‡๏ธ ['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.

index.js
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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee