Great Gale
Great Gale

Reputation: 71

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!!

Upvotes: 2

Views: 3866

Answers (4)

trincot
trincot

Reputation: 351158

I would use this regular expression: (\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);

Upvotes: 3

Kamil Naja
Kamil Naja

Reputation: 6692

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

Upvotes: 1

fig
fig

Reputation: 384

First, split the list into an array array = str.split(" ") and initialize an empty string 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 = 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!

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37775

You can use replace method of string.

   (.*?\s.*?\s)
  • .*?- Match anything except new line. lazy mode.
  • \s - Match a space character.

let string = "example string is cool and you're great for helping out" 

console.log(string.replace(/(.*?\s.*?\s)/g, '$1'+'\n'))

Upvotes: 6

Related Questions