美文网首页
单词超过一定长度,换行

单词超过一定长度,换行

作者: Frank_Fang | 来源:发表于2023-03-26 19:07 被阅读0次
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    
    <body>
        <script>
            function textWrap(text, maxNum) {
                if (!maxNum) {
                    return text
                } else {
                    let str = ''
                    let tmp = ''
                    const arr = text.split(' ')
                    arr.forEach((item) => {
                        if (!tmp) {
                            if (item.length >= maxNum) {
                                str = str + item + '\n'
                            } else {
                                tmp = item
                            }
                        } else {
                            if (tmp.length + item.length >= maxNum) {
                                str = str + tmp + '\n' + item + '\n'
                                tmp = ''
                            } else {
                                tmp = tmp + ' ' + item
                            }
                        }
                    })
                    return str
                }
            }
            console.log(textWrap('Welcome to our school, 7'))
            console.log(textWrap('Welcome to our school', 7))
            console.log(textWrap('Andrew Philip James John Job Matthew Bartholomew, 10'))
            console.log(textWrap('Andrew Philip James John Job Matthew Bartholomew', 10))
    
        </script>
    
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:单词超过一定长度,换行

          本文链接:https://www.haomeiwen.com/subject/wtqardtx.html