Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement