Start learning free

LESSON 623 OF 671 · PROJECTS: COMMAND-LINE TOOLS

Tr V1 in JavaScript: Swapping One Character with split and join

Practice Read the full explanation

Build a tiny version of the Unix tr command. Given a list of lines and two single characters fromChar and toChar, replace every occurrence of fromChar with toChar in each line, then return the lines joined by newline characters (\n).

Notes: fromChar and toChar are single ASCII characters, taken literally (no escapes like \, no ranges). Upper and lower case are different characters. A line may be empty, and may not contain fromChar at all.

Function signature:

tr(lines, fromChar, toChar)

Example:

Input: lines = ["banana", "apple"], fromChar = "a", toChar = "X"

Output: "bXnXnX\nXpple"

When printed:
bXnXnX
Xpple

JavaScript's replace only swaps the first occurrence. To replace ALL of them with a literal char, the easiest trick is line.split(fromChar).join(toChar).

The full solution:
class Solution {
    tr(lines, fromChar, toChar) {
        let result = [];
        for (let i = 0; i < lines.length; i++) {
            result.push(lines[i].split(fromChar).join(toChar));
        }
        return result.join("\n");
    }
}

STEP 1 OF 4
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Tr V1 in JavaScript, explained

    Problem overview

    This is the first version of a small tr command. The method tr(lines, fromChar, toChar) receives an array of lines and two single characters. It replaces every occurrence of fromChar with toChar in each line and returns the lines joined by \n.

    The characters are taken literally, with no escapes or ranges, and upper and lower case are different characters. A line may be empty, or may not contain fromChar at all. In that case it is returned unchanged.

    For ["banana", "apple"] with fromChar = "a" and toChar = "X", the result is "bXnXnX\nXpple".

    Approach: split at the character, join with the new one

    The obvious tool is replace, but with a string as the first argument it changes only the first match: "banana".replace("a", "X") is "bXnana". Replacing everything with replace would need a regular expression, and then characters such as . would have special meaning.

    The lesson uses a different idea. line.split(fromChar) cuts the line at every fromChar and drops the separators: "banana".split("a") is ["b", "n", "n", ""]. Then join(toChar) glues the pieces back together with toChar between each two. Every cut becomes one replacement. A string separator is matched literally, so the character . is just a dot.

    Each line is processed that way and collected in an array, and one final join("\n") builds the output.

    Step by step

    1. Create result as an empty array. The swapped lines collect there.
    2. Loop over the lines with an index i from 0 while i < lines.length.
    3. Swap inside the loop. Push lines[i].split(fromChar).join(toChar) onto result.
    4. After the loop, return result.join("\n"). The separator goes only between lines, so there is no newline after the last one.

    The solution in JavaScript

    class Solution {
        tr(lines, fromChar, toChar) {
            let result = [];
            for (let i = 0; i < lines.length; i++) {
                result.push(lines[i].split(fromChar).join(toChar));
            }
            return result.join("\n");
        }
    }
    

    The JavaScript details:

    • Strings are immutable. No method changes a string in place. split and join return new values, so the input lines stay as they were.
    • A line without fromChar survives. "cherry".split("z") is the one-element array ["cherry"], and joining a single element adds no separator.
    • An empty line stays empty. "".split("a") is [""], which joins to "".
    • The same word, two jobs. The inner join(toChar) glues characters back inside one line, and the outer join("\n") glues lines together. They are different calls on different arrays.
    • Another way. replaceAll(fromChar, toChar) also replaces every match when given strings. The lesson's steps use split and join, which work the same way here.

    Complexity

    Let N be the total number of characters in all lines.

    Time: O(N). Each line is scanned once by split, and the pieces are copied once by join. The final join is also linear.

    Space: O(N) for the temporary pieces of one line, the result array and the output string.

    Edge cases and common mistakes

    • Using replace. It changes only the first occurrence, so "banana" would become "bXnana" instead of "bXnXnX".
    • Special characters. With fromChar = "." and toChar = "-", ["a.b.c"] gives "a-b-c". Because split receives a string, the dot is not treated as "any character".
    • Case matters. ["Aa"] with "a" and "b" gives "Ab": the capital letter is a different character and is left alone.
    • Empty lines are kept. ["abc", ""] with "z" and "y" gives "abc\n": two lines, the second empty.
    • Replacement text with a backslash. The replacement is taken literally here too: ["a-b"] with "-" and "\\" (a single backslash character) gives the text a\b, which prints with one backslash.
    • Returning the array. The method must return a string. Forgetting the final join returns an array.

    Testing

    • ["banana", "apple"], "a", "X" gives "bXnXnX\nXpple".
    • ["a.b.c"], ".", "-" gives "a-b-c".
    • ["Aa"], "a", "b" gives "Ab".
    • ["abc", ""], "z", "y" gives "abc\n".
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free