Skip to content

Instantly share code, notes, and snippets.

@MaraAlexa
Created April 29, 2017 09:20
Show Gist options
  • Save MaraAlexa/db90d025ef1bfff230930ff402547b14 to your computer and use it in GitHub Desktop.
Save MaraAlexa/db90d025ef1bfff230930ff402547b14 to your computer and use it in GitHub Desktop.
Combine Values of an Array into a String with Join
// Array.prototype.join();
var name = ['Shane', 'Osbourne'];
// give all the values back as a string and I provide the separator in between
console.log(names.join(' ')); // Shane Osbourne with a space in between
console.log(names.join('-')); // Shane-Osbourne
console.log(names.join('')); // ShaneOsbourne
console.log(names.join()); // when not providing any arg at all, you get the values separated with a comma -> Shane,Osbourne
// practical USE CASE:
/*
1.Lets say you have a command line program and you want to provide a help screen to users;
*/
// store each line of the help text in an array
var help = [
'Usage',
' foo-app <input>'
]
// check if the user has run the 'help' command by looking at the third argument available tools
if(process.argv[2] === 'help'){
console.log(help.join('\n')); // takes every item in the help array, puts a new line in between each one and prints the result
}; // prints the values from the help array in the terminal (when users run help in the terminal):
/*
Usage
foo-app <input>
*/
/*
2. You want to Upper Case the first letter of each word in a String
*/
var name = 'shane osbourne';
var upper = name.split(' ') // [shane, osbourne]
.map(x => x.charAt(0).toUpperCase() + x.slice(1)) // produces another array: [Shane, Osbourne]
.join(' '); // creates a string: 'Shane Osbourne'
console.log(upper); // 'Shane Osbourne'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment