因此,在我的程序中,我可以接收各种长度的字符串并将它们发送出去以进行翻译。如果这些字符串具有一定的字符长度,我会收到错误,因此我想在此之前检查并拆分这些字符串(如果有必要)。但我不能只在单词中间分割字符串,单词本身也需要完整并考虑在内。
例如:
let str = "this is an input example of one sentence that contains a bit of words and must be split"
let splitStringArr = [];
// If string is larger than X (for testing make it 20) characters
if(str.length > 20) {
// Split string sentence into smaller strings, keep words intact
//...
// example of result would be
// splitStringArr = ['this is an input', 'example of one sentence' 'that contains...', '...']
// instead of ['this is an input exa' 'mple of one senten' 'ce that contains...']
}
但我不知道如何分割句子并仍然考虑句子的长度。
解决方案是否是迭代字符串,将每个单词添加到其中并每次检查它是否超过最大长度,否则启动一个新的数组索引,或者是否有更好/现有的方法?
您可以使用匹配、前瞻和单词边界,|.+
注意末尾的字符串小于末尾的最大长度
let str = "this is an input example of one sentence that contains a bit of words and must be split"
console.log(str.match(/\b[\w\s]{20,}?(?=\s)|.+$/g))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)