This tutorial will teach you how to split the string and trim surrounding spaces.
let str = " React , Angular , Vue "; let arr = (str.split(',')); console.log(arr); //[" React ", " Angular ", " Vue "] let result = arr.map(element => element.trim()); console.log(result); //["React", "Angular", "Vue"]
Explanation of the code:
Using the split()
method, you split the string. The split()
method breaks the string based on the argument passed to it, and it returns an array of substrings.
let str = " React , Angular , Vue "; let arr = (str.split(',')); console.log(arr); //[" React ", " Angular ", " Vue "]
If the array elements have the leading and trailing spaces, then call the map() method to iterate over the array. On each iteration, use the trim() method to remove the surrounding spaces.
let result = arr.map(element => element.trim()); console.log(result); //["React", "Angular", "Vue"]
You might find a scenario in which more than one separator character is next to one another. In that case, calling the split() method will get empty strings as array elements.
To handle this situation, use the array filter() method to eliminate empty strings from the array.
let str = " React ,, Angular ,, Vue "; let arr = (str.split(',')); console.log(arr); //[" React ", "", " Angular ", "", " Vue "] let result = arr.map(element => element.trim()).filter(element => element); console.log(result); //["React", "Angular", "Vue"]
The filter() method simply returns an element because an empty string in JavaScript is considered a false value. Therefore, when the filter() method returns false for an element, that element does not become a part of the new array.