Using split(), map() and trim()
The split() method converts a string to an array of substrings based on a separator. You can find its syntax and usage here. The map() method creates a new array by calling a function on every element in the calling array. Here defines its syntax and usage. The trim() method will trim (remove) the surrounding spaces of a string.
let text = ' Hello everyone, welcome to our page, Learn Share IT '; // Split string separated by a comma let substrings = text.split(','); // Trim surrounding spaces in every element (every substring) let res = substrings.map(s => s.trim()); console.log(res);
['Hello everyone', 'welcome to our page', 'Learn Share IT']
The above example shows that we have a string with surrounding spaces (at the beginning and at the end). We first split the strings into an array of substrings using split(),and then we used map(), which calls the trim() method on every element of the array in order to trim surrounding spaces. The result is an array of trimmed substrings.
Using lodash _.split(), _.trim and _.map()
This method needs importing from a library named lodash. You have to import this library by inserting this <script> tag on your page:
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
- arr: the array containing the split strings.
- Foo: the function to apply to each element in the array
This _.map() method also returns an array as the previous solution. You can read the _.split() method here. Let’s see how we achieve this using a lodash library:
Hello everyone,welcome to our page,Learn Share IT
Have you recognized the differences between the methods of lodash and the built-in methods? In the first approach, the split() and map() methods require only 1 argument, whereas, in the lodash, these methods require two arguments. Although this solution may need to import an external library, it also gives out the expected results as the first one.
Note that the result (“res” variable) in this example is an array, it is converted automatically to a string by the system machine; therefore the substrings (the elements of the array) are separated by a comma (default delimiter) as displayed.
Maybe you are interested:
Name of the university: HCMUT