Home > katas > Remove String Spaces (8kyu) [TypeScript]

Remove String Spaces (8kyu) [TypeScript]


Chek kata on Codewars

Description:

Simple, remove the spaces from the string, then return the resultant string.

Solution 1.1

Let's start with a loop solution.

function noSpace(x:string):string {
    let newStr = ''
    for (let i = 0; i < x.length; i++) {
        if (x[i] !== " ") {
            newStr += x[i]
        }
    }
    return newStr
}

Solution 2.1

Let's solve it with regular expression.

function noSpace(x:string):string {
    return x.replace(/ /g, '')
}

Solution 3.1

Let's solve it with split and join.

function noSpace(x:string):string {
    return x.split(" ").join('')
}

Solution 3.2

Let's solve it with split and filter.

function noSpace(x:string):string {
    return x.split("").filter(i => i !== ' ').join('')
}

Solution 3.3

Let's solve it with split and reducer.

function noSpace(x:string):string {
    return x.split(" ").reduce((a, c) => a + c)
}
© 2021, Andrew Losseff