STRINGS
1 //generate two randomly interger which is in [1,6] 2 const die1 = Math.floor(Math.random() * 6) + 1; //random number from 1-6 3 const die2 = Math.floor(Math.random() * 6) + 1; //random number from 1-6 4 5 // creat a new variable called roll, which will be a string that displays each die as well as their sum 6 //eg output: "You rolled a 3 and a 5. They sum to 8" 7 let roll = `"You rolled a ${die1} and a ${die2}. They sum to ${die1 + die2}"`;
1 // Making Strings 2 let color = "purple"; 3 4 // Single quotes work too: 5 let city = ‘Tokyo‘; 6 7 //Strings have a length: 8 city.length; //5 9 10 //We can access specific characters using their index: 11 city[0]; //‘T‘ 12 city[3]; //‘y‘ 13 14 // String methods: 15 ‘hello‘.toUpperCase(); // "HELLO"; 16 ‘LOL‘.toLowerCase(); // "lol" 17 ‘ omg ‘.trim(); // "omg" 18 19 // String methods with arguments: 20 // ============================== 21 22 //indexOf returns the index where the character is found (or -1 if not found) 23 ‘spider‘.indexOf(‘i‘); //2 24 ‘vesuvius‘.indexOf(‘u‘); //3 - only returns FIRST matching index 25 ‘cactus‘.indexOf(‘z‘); //-1 not found
26 27 // slice - returns a "slice" of a string 28 "pancake".slice(3); //"cake" - slice from index 3 onwards 29 "pancake".slice(0, 3); //"pan" - slice from index 0 up to index 3 30 31 // replace - returns a new string, with the FIRST match replaced 32 "pump".replace("p", "b"); //"bump" - only replaces first "p" 33 34 // String Template Literals 35 // Use backtick characters, NOT SINGLE QUOTES! 36 // ======================== 37 const color = "olive green"; 38 const msg = `My favorite color is: ${color}` //"My favorite color is: olive green" 39 40 const str = `There are ${60 * 60 * 24} seconds in a day`//"There are 86400 seconds in a day"
原文:https://www.cnblogs.com/LilyLiya/p/14244377.html