将字符串按单词分割成块

问题描述 投票:0回答:1

一些 JS 框架允许将 HTML 作为参数,但不能进行自动换行。所以你必须通过添加换行标签来准备字符串。

如何将字符串拆分为给定长度的单词并用分隔符将它们粘在一起?

javascript string split
1个回答
0
投票

让我们比较一些方法:

var text = 'This is a long sentence. Another long for a test!!!'

// 1. Not working good. Cuts last word!
var first =  text.match(/\b(\w+\W+\w+\W+\w+\W+)/g);

// 2. Works better? but may cause problems with another texts!
var second = text.match(/[a-zA-Z]+(?:[^a-zA-Z]+[a-zA-Z]+){0,3}([^a-zA-Z]*){0,}/g);

// 3. Working solution, but needs more CPU ant time
var third = [];
var words = text.split(" ");

const chunkSize = 3;
for (let i = 0; i < words.length; i += chunkSize) {
    const chunk = words.slice(i, i + chunkSize);
    third.push(chunk.join(" "));
}

// 4. Best solution for DRY compliance
const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );

function str_split(text, chunkSize=3, glue='<br/>')
{
    var res = [];
    
    chunk(text.split(" "), chunkSize).forEach((ch) => {
      res.push(ch.join(" "));
    })
    
    return res.join(glue);
}

console.log(first.join("<br/>"));
console.log(second.join("<br/>"));
console.log(third.join("<br/>"));
console.log(str_split(text));
© www.soinside.com 2019 - 2024. All rights reserved.