Skip to content

Latest commit

 

History

History
22 lines (18 loc) · 553 Bytes

File metadata and controls

22 lines (18 loc) · 553 Bytes

Given a string and a number n, replace every nth character with '_'.
"foreigner", 2 => "f_r_i_n_r"
"leetcode", 3 => "le_tc_de"
"leetcode", 1 => "________"

function replaceCharacter(str, num) {
    let new_str = str.split(""); // gives array of type string
    let n = num; // n = 2
    // for loop T.C: O(n) S.C: O(1)
    for(let i = 0; i < new_str.length; i++) {
        if(i === n - 1) { // i === 1
            new_str.splice(i, 1, "_")
            n += num;
        }
    }
    return new_str.join("")
}