gpt4 book ai didi

javascript - 是否可以仅在超过 5 个单词的字符串上每 5 个单词插入
标记,并添加
与 "."(点)

转载 作者:行者123 更新时间:2023-12-02 22:34:50 25 4
gpt4 key购买 nike

我想插入<br>进入我的绳子。规则:

  • 插入<br>每次经期后。
  • 插入<br>每 5 个字之后。

例如:

This is a string. For demo to split the text. If its long more then 5 characters. But some string is short. And it will not split. the short length string it will only split the long string which is more then 5 words.";

期望的输出:

This is a string.<br>For demo to split the<br>text.<br> If its long more then<br>5 characters.<br>But some string is short.<br>And it will not split.<br>The short length string it<br>will only split the long<br>string which is more then<br>5 words.

我怎样才能做到这一点?

最佳答案

使用正则表达式匹配 5 个非空格序列(其中非空格不包含 . ),或匹配 . 。然后插入<br>赛后:

const str = "This is a string. For demo to split the text. If its long more then 5 characters. But some string is short. And it will not split. the short length string it will only split the long string which is more then 5 words.";

const output = str.replace(
/(?:[^\s.]+\s+){5}|\./g,
'$&<br>'
);
console.log(output);

(?:[^\s.]+\s+){5} - 重复(非空格字符,后跟空格字符)5次,其中非空格字符不包含.

\. - 或者,匹配文字 .

'$&<br>' - 替换为匹配的字符串,并与 <br> 连接之后

请注意您的str实际上是一个数组,而不是字符串 - 更精确的变量名称可以提高代码清晰度并减少错误,您可能希望修复该问题。

关于javascript - 是否可以仅在超过 5 个单词的字符串上每 5 个单词插入 <br> 标记,并添加 <br> 与 "."(点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58776160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com