我有这个字符串:
这是一个由代码分割的句子,我如何将其缩小为最多30个字符?
我想将其放入Javascript的此数组中:
[
"This is a sentence to be split",
"by the code, how can I make",
"it smaller with maximum",
"number of 30 characters?"
]
如何使用Javascript拆分该字符串,每个句子拆分的最大长度为30个字符,整个单词?
我发现此代码:
How do I split a string at a space after a certain number of characters in javascript?
那做得很好,但是它发现了30个字符限制之后的空格,而不是在它之前:
function myFunction() {
str = "This is a sentence to be split by the code, how can I make it smaller with maximum number of 30 characters?"
result = str.replace(/.{30}\S*\s+/g, "$&@")
document.getElementById("demo").innerHTML = result;
}
最佳答案
为了避免在每个部分的开头或结尾出现空格,请使用:
var str = "This is a sentence to be split by the code, how can I make it smaller with maximum number of 30 characters?";
console.log(str.match(/\S.{0,29}(?=\s+|$)/g));
关于javascript - 如何在不剪切单词的情况下将一个句子拆分为最多字符数的句子数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58542477/