javascript - 如何用星号框住字符串?
问题描述
我尝试构建一个函数,该函数将仅使用 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.
解决方案
也许您应该计算字符串的长度并使用它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.'))
推荐阅读
- bing-api - S1 Bing Web Search API 每日用户搜索限制?付费订阅
- php - 我从 php 标签传递会话,然后尝试根据使用 jquery 的 if 语句在页面加载时隐藏和显示 div
- python-3.x - 如何在 python 中动态遍历特定键?
- regex - 正则表达式搜索/替换中的 URL 转换
- json - 无法使用 React 从 json 加载图像
- firefox - Firefox、Charis SIL 和塞尔维亚草书
- batch-file - 如何逐行读取和打印文本文件的内容?
- linux - Linux 内核编译错误 Unsupported NR_CPUS for lb tracepoint
- javascript - 正则表达式:字符串匹配,包括标点符号
- tensorflow - 从头开始训练 Inception V2 - 发散