Search code examples
javascriptstringtrim

Detect a string if it is trimmed or not


`......................
..#................#..
..#..............=.#..
..#.........o.o....#..
..#.@......#####...#..
..#####............#..
......#++++++++++++#..
......##############..
......................`.trim()

When I trim the above, it gives me this:

"......................
..#................#..
..#..............=.#..
..#.........o.o....#..
..#.@......#####...#..
..#####............#..
......#++++++++++++#..
......##############..
......................"

From my understanding, trim removes the whitespace from the beginning and end of the string like in " helloworld ", the trim will be "helloworld". Now I want to know about the first example that I've defined up above.

First of all, is it even a string because I see backticks there. And if I try to give it quotes the trim won't work. I can't understand or see how it is trimmed. The example is from the platform game in Eloquent JavaScript.


Solution

  • This is not valid in js:

    "......................
    ..#................#..
    ..#..............=.#..
    ..#.........o.o....#..
    ..#.@......#####...#..
    ..#####............#..
    ......#++++++++++++#..
    ......##############..
    ......................"
    

    This is (as Kunal Mukherjee pointed out in the comments you have to use template literals, which support multiple lines):

    `......................
    ..#................#..
    ..#..............=.#..
    ..#.........o.o....#..
    ..#.@......#####...#..
    ..#####............#..
    ......#++++++++++++#..
    ......##############..
    ......................`
    

    To answer the question in your title, to check if a string is trimmed you can do this:

    function isTrimmed(str) {
      return str == str.trim();
    }
    
    const foo = `......................
    ..#................#..
    ..#..............=.#..
    ..#.........o.o....#..
    ..#.@......#####...#..
    ..#####............#..
    ......#++++++++++++#..
    ......##############..
    ......................`;
    
    console.log(isTrimmed(foo));
    
    console.log(isTrimmed(" Text with space "));