字符串文字中的TypeScript空行

2vuwiymt  于 2022-11-26  发布在  TypeScript
关注(0)|答案(1)|浏览(161)

我想创建一个字符串文字,其可选值为numberOfResidents。

function mapBuildingToComment(building: Building) {
    return `
    ### Building information ###
    Street: ${building.address.street}
    HouseNumber: ${building.address.houseNumber}
    ${mapNumberOfResidents(building.numberOfResidents)}
    City: ${building.address.city}
    `
}

function mapNumberOfResidents(numberOfResidents?: string) {
    if (!numberOfResidents) return ''

    return `Number of residents: ${numberOfResidents}`
}

我现在的问题是,当numberOfResidents未定义时,输出中有一个空行。

Output:
    ### Building information ###
    Street: Teststreet
    HouseNumber: 1

    City: Test

如何做到没有空行,门牌号正下方是城市?

yqhsw0fo

yqhsw0fo1#

删除换行符,并仅在需要时添加它,如

function mapBuildingToComment(building: typeof b) {
    return `
    ### Building information ###
    Street: ${building.address.street}
    HouseNumber: ${building.address.houseNumber}\
${building.numberOfResidents ? '\n    ' + mapNumberOfResidents(building.numberOfResidents) : ''}
    City: ${building.address.city}
    `
}

function mapNumberOfResidents(numberOfResidents?: string) {
    if (!numberOfResidents) return ''

    return `Number of residents: ${numberOfResidents}`
}

const b = {address: {street: '123', houseNumber: 245, city: 'asd'}, numberOfResidents: '3'}
console.log(mapBuildingToComment(b))
b.numberOfResidents = ''
console.log(mapBuildingToComment(b))

另一个选择是从s.replaceAll(/\n\s+(?=\n)/g, '')结果中删除空行

相关问题