Join() and split() in javascript

In Javascript course in the Array section, Mosh gives an example that takes a string and transform it in an array using the split() method, and then he takes this array and transform it back in a string using the join() method:

const message = 'This is my first message';
const parts = message.split(' ');

//output: (5) ['This', 'is', 'my', 'first', 'message']

const combined = parts.join('-');

//output: This-is-my-first-message

why would we need to take a string, transform it into an array, and then back to a string?

Well, in the example you’ve provided, the string 'This-is-my-first-message' that has been created by joining parts is different from the initial string 'This is my first message' as in the newer string, spaces have been replaced by dashes.
There can be other similar use cases where you might want to replace a certain character with some other character in a string. Of course, you can achieve the same thing as done in the example using replace string method like 'This-is-my-first-message'.replace(/ /g, '-') but it’s just another (and simpler) way of doing it.

1 Like

Have you ever wonder how you can create a slug
look into the link of this question

when you submitted this question you have wrote something like this Join() and split() in javascript it ended up join-and-split-in-javascript

1 Like