Start learning free

LESSON 371 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: cat v3 — Show Special Chars (-A) in JavaScript

Practice

Now build the -A flag of the cat tool, as a new function. It makes whitespace visible: every tab character (\t) is replaced by the two characters ^I and every line ends with a literal $ marker (so trailing spaces become obvious). Lines are then joined with newlines.

Note: real cat -A also shows other control characters (such as ^M) and non-ASCII bytes; this version only handles tabs and line ends, like cat -T -E. A blank line becomes just $, and an empty list gives an empty string.

Function signature:

showAllCat(lines)

Example:

Input: lines = ["hello\tworld", "foo"]

Output: "hello^Iworld$\nfoo$"

When printed:
hello^Iworld$
foo$

Another example (a blank line, trailing spaces):

Input: lines = ["a\t", "", "x  "]

Output: "a^I$\n$\nx  $"

When printed:
a^I$
$
x  $

Two transformations per line: replace every tab with "^I", then append "$". After both, join all the transformed lines with "\n".

A simple way to replace ALL tabs is line.split("\t").join("^I"). Then concatenate "$":
lines[i].split("\t").join("^I") + "$"


The full solution:
class Solution {
    showAllCat(lines) {
        let out = [];
        for (let i = 0; i < lines.length; i++) {
            out.push(lines[i].split("\t").join("^I") + "$");
        }
        return out.join("\n");
    }
}

STEP 1 OF 4
    Ctrl + Enter to check

    Cat V3 in JavaScript

    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free