<!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>
网友评论