JavaScript 字符串中每两个单词换行一次

Gre*_*ale 2 javascript

我有一根绳子

string = "example string is cool and you're great for helping out" 
Run Code Online (Sandbox Code Playgroud)

我想每两个单词插入一个换行符,这样它就会返回:

string = 'example string \n
is cool  \n
and you're  \n
great for \n
helping out'
Run Code Online (Sandbox Code Playgroud)

我正在使用变量,无法手动执行此操作。我需要一个可以接受这个字符串并为我处理它的函数。

谢谢!!

Cod*_*iac 6

您可以使用字符串的替换方法。

   (.*?\s.*?\s)
Run Code Online (Sandbox Code Playgroud)
  • .*?- 匹配除新行之外的任何内容。懒惰模式。
  • \s- 匹配空格字符。