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

javascript字符串中每两个单词换行一次,javascript,Javascript,我有一根绳子 string = "example string is cool and you're great for helping out" 我希望每两个单词插入一个换行符,以便它返回以下内容: string = 'example string \n is cool \n and you're \n great for \n helping out' 我正在处理变量,无法手动执行此操作。我需要一个函数,可以接受这个字符串,并为我处理它 谢谢 您可以使用字符串的替换方法 (.

我有一根绳子

string = "example string is cool and you're great for helping out" 
我希望每两个单词插入一个换行符,以便它返回以下内容:

string = 'example string \n
is cool  \n
and you're  \n
great for \n
helping out'
我正在处理变量,无法手动执行此操作。我需要一个函数,可以接受这个字符串,并为我处理它


谢谢

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

   (.*?\s.*?\s)
*?-匹配除新线以外的任何内容。懒惰模式。 \s-匹配空格字符。 let string=示例string很酷,您非常乐于助人
console.logstring.replace/*?\s.*?\s/g,$1'+'\n'我将使用以下正则表达式:\s+\s*{1,2}:

var string=example string很酷,你很乐于助人; var result=string.replace/\S+\S*{1,2}/g,$&\n;
console.logresult 首先,将列表拆分为array=str.split并初始化空字符串var newstring=。现在,循环遍历所有数组项,并使用换行符array.foreachFunction将所有内容添加回字符串,i{newstring+=e+;ifi+1%2=0{newstring+=\n};} 最后,你应该:

array = str.split(" ");
var newstring = "";
array.forEach(function(e, i) {
    newstring += e + " "; 
    if((i + 1) % 2 = 0) {
        newstring += "\n ";
    }
})

newstring是带有换行符的字符串

您尝试了什么?我一直在研究concat选项,我知道js6使添加带有回勾的换行符变得非常容易。问题是我不知道如何告诉我的函数在每两个单词中添加它。匹配单词的起点+1。似乎在每一个单词后都会正确地添加一行,而不是在投票最多的答案中出现的每一秒空白。
let str = "example string is cool and you're great for helping out" ;

function everyTwo(str){
    return str
        .split(" ") // find spaces and make array from string
        .map((item, idx) => idx % 2 === 0 ? item : item + "\n") // add line break to every second word
        .join(" ") // make string from array
}

console.log(
    everyTwo(str)
)

output => example string
 is cool
 and you're
 great for
 helping out