-5

I try to build a function that will frame me a string with asterisks, using only JS. How can I do it?

function frame('Good Morning')

should get >>>

****************
* 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.
  • 1
    What have you tried? Where are you stuck? – John Coleman Jul 07 '19 at 18:30
  • Possible duplicate of [How to force a line break on a Javascript concatenated string?](https://stackoverflow.com/questions/15357846/how-to-force-a-line-break-on-a-javascript-concatenated-string) – adiga Jul 07 '19 at 18:35
  • Thank you for all the answers - it seems that my problem was to understand how to break the lines of asterisks. – Mathsteacher7 Jul 07 '19 at 21:30

2 Answers2

3

Perhaps you should calculate the length of the string and use that with repeat() to make the borders:

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'))

If you want to be a little crazier, you can split on new lines and accept multi-line input. This uses reduce to build the inner strings and padEnd to pad with spaces:

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.'))
Mark
  • 90,562
  • 7
  • 108
  • 148
0

Did you mean something like this?

EDIT

    function frame(str){
        var border="";
        for(i=0;i<str.length+4;i++){
            border += "*"
        }
        return border + "\n* "+str+" *\n" + border;
        
    }
    console.log(frame("Hello World"));
LIGHT
  • 5,604
  • 10
  • 35
  • 78
  • Sorry, I did that before edit was made to the question – LIGHT Jul 07 '19 at 18:34
  • The only problem is that the asterisks in the beginning and in the end are not the line above and below. – Mathsteacher7 Jul 07 '19 at 18:36
  • Okay, now I see after you edit it. Thank you it is working almost perfect, I need to clean there something, but in general, I understood now how to jump between the lines. – Mathsteacher7 Jul 07 '19 at 18:40