首页 > 解决方案 > 如何
在每 5 个单词后将标签放在一个长字符串中?

问题描述

例子:

let str = "Hello this is a test string to figure out how is it possible to split a long string into multiple string";

我想<br>在每 5 个单词之后放置标签,如下所示:

let str1 = "Hello this is a test<br>string to figure out how<br>is it possible to split<br>a long string into multiple<br>string";

我怎样才能做到这一点?

标签: javascript

解决方案


您可以split将字符串放在空格上,map将结果的元素转换为Array以空格开头的单词或每第 6 个单词,<br>然后join将结果返回到 a String。就像是:

const str2Split = "Hello this is a test string to figure out how is it possible to split a long string into multiple string";

const withAddedBreaks = str2Split.split(" ") 
  .map( (v, i) => `${i && i % 5 == 0 ? "<br>" : " "}${v}`);
//                   ^ insert <br> after every 5 words, otherwise a space
console.log(withAddedBreaks.join("").trim());
//                                   ^ remove first space

console.log(`use method: replace every 4rd space with " !#! "\n${
  replaceEveryNthSpace(str2Split, 3, " !#! ")}`);

// a method for it
function replaceEveryNthSpace(str, n, substr) {
  return str
  .split(" ") 
  .map( (v, i) => `${i && i % n == 0 ? substr : " "}${v}`)
  .join("")
  .trim();
}


推荐阅读