单词超过一定长度,换行

2023-03-26  本文已影响0人  FrankFang7
<!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>
上一篇 下一篇

猜你喜欢

热点阅读