Graduate Program KB

Strings

Template Strings

  • Interpolation, allows you to use variables or expressions inside of the string
    const var1 = 123
    const var2 = "David"
    const msg = 
    `Hello ${var1} 
    ${var2}`
    //msg = Hello 1
    //      23 David

Tagged Literals Templates

  • Tagging a string allows you to execute a function before creating the string, pre processing
    function functionCall(strings,...values){
        //Go through each string char and do stuff
        //return string or anything
    }

    const var1 = 12.34;
    const msg = functionCall //Tag Function
    `Message blah ${var1}`
    //depending on what the function does, it will pre process the string
  • Tag functions allow you to format strings in many different ways.
  • Can write regex inside tagged literals

Padding and Trimming

  • Padding is adding characters
    const str = "Hello"
    str.padStart(5) // "Hello"
    str.padStart(8) // "___Hello" _ in this case are spaces
    str.padStart(8,"*") // "***Hello
    str.padStart(8,"12345") // 123Hello"
    str.padStart(8,"ab") // "abbHello"
  • Trimming gets rid of whitespace
    const str = "    Hello David " //4 spaces at start, 1 space at end.
    str.trim() //"Hello David"
    str.trimStart() //"Hello David "
    str.trimEnd() //"    Hello David"

    //trim() doesn't affect spaces in the middle
    //const str2 = "Hello   World"
    //After trimming the 3 spaces still in middle