首页 > 解决方案 > 如何用星号框住字符串?

问题描述

我尝试构建一个函数,该函数将仅使用 JS 构建一个带星号的字符串。我该怎么做?

function frame('Good Morning')

应该得到>>>

****************
* Good Morning *
****************

Edit after having to see some answers - the main problem was to break the line of asterisks so it will look as in the example, and not just long lines of asterisks.

标签: javascript

解决方案


也许您应该计算字符串的长度并使用它repeat()来制作边框:

function frame(str){
    let border = '*'.repeat(str.length + 4)
    return `${border}\n* ${str} *\n${border}`
}

console.log(frame('Good Morning'))
console.log(frame('A longer string with more words'))

如果你想更疯狂一点,你可以在新行上拆分并接受多行输入。这用于reduce构建内部字符串并padEnd用空格填充:

function frame(str){
    let lines = str.split('\n')
    // get length of longest line:
    let max_length = Math.max(...lines.map(l => l.length))
    let border = '*'.repeat(max_length + 4)

    let ret =  border + "\n"
    // make inner lines padded to length:
    ret += lines.reduce((s,l) => s+=`* ${l.padEnd(max_length)} *\n`, "")
    ret += border
    return ret
}

console.log(frame('Good Morning'))
console.log(frame('A longer string with more words'))
console.log(frame('A longer string with more words\nand more lines\nwrapped into a nice box.'))


推荐阅读