javascript - 如何
在每 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";
我怎样才能做到这一点?
解决方案
您可以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();
}
推荐阅读
- java - 如何处理在 finally 块中关闭连接时引发的异常?
- java - 使 JLabel 文本与中心垂直对齐
- html - 我尝试在使用 angularjs 上传多个图像之前进行预览,但没有一个显示?
- c++ - std::shared_mutex 通过 thread_local 存储递归保护
- android - 带有子元素和根的 LinearLayout 是一个滚动视图。它应该被包装到另一个滚动视图吗?
- flutter - Flutter 地理定位器插件 Geolocator().placemarkFromAddress() 和 Geolocator().placemarkFromCoordinates() 不起作用
- javascript - 递归函数在Javascript中运行时如何执行回调函数?
- javascript - 如何显示带有动态变量的 toastr 消息
- r - R:在销售数据中插入缺失观察的行
- sql - 如何加入多个表进行计数?