[英]New line break every two words in javascript string
I have one string 我有一串
string = "example string is cool and you're great for helping out"
I want to insert a line break every two words so it returns this: 我想每两个单词插入一个换行符,因此它返回以下内容:
string = 'example string \n
is cool \n
and you're \n
great for \n
helping out'
I am working with variables and cannot manually do this. 我正在使用变量,无法手动执行此操作。 I need a function that can take this string and handle it for me.
我需要一个可以接受此字符串并为我处理的函数。
Thanks!! 谢谢!!
You can use replace method of string. 您可以使用字符串的替换方法。
(.*?\s.*?\s)
.*?
- Match anything except new line. \\s
- Match a space character. \\s
匹配一个空格字符。 let string = "example string is cool and you're great for helping out" console.log(string.replace(/(.*?\\s.*?\\s)/g, '$1'+'\\n'))
I would use this regular expression: (\\s+\\s*){1,2}
: 我将使用以下正则表达式:
(\\s+\\s*){1,2}
:
var string = "example string is cool and you're great for helping out"; var result = string.replace(/(\\S+\\s*){1,2}/g, "$&\\n"); console.log(result);
First, split the list into an array array = str.split(" ")
and initialize an empty string var newstring = ""
. 首先,将列表拆分为一个数组
array = str.split(" ")
并初始化一个空字符串var newstring = ""
。 Now, loop through all of the array items and add everything back into the string with the line breaks array.forEach(function(e, i) {newstring += e + " "; if((i + 1) % 2 = 0) {newstring += "\\n "};})
In the end, you should have: 现在,遍历所有数组项,并使用换行符
array.forEach(function(e, i) {newstring += e + " "; if((i + 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
is the string with the line breaks! newstring
是带有换行符的字符串!
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.