2

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

Serge K.
  • 5,303
  • 1
  • 20
  • 27
Great Gale
  • 71
  • 1
  • 8
  • 2
    What did you tried ? – Serge K. Feb 20 '19 at 16:41
  • I've been looking into concat options and I know that js6 makes it pretty easy to add in line breaks with back ticks. The problem is I have no idea how to tell my function to add it in every two words. – Great Gale Feb 20 '19 at 16:45
  • starting point to match a word https://stackoverflow.com/questions/1751301/regex-match-entire-words-only – epascarello Feb 20 '19 at 16:45

4 Answers4

6

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'))
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
3

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);
trincot
  • 317,000
  • 35
  • 244
  • 286
  • +1. Appears to correctly add a new line after every second word, and not every second white space as appears in the most up-voted answer. – Gary Thomas Feb 20 '19 at 16:57
1

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!

fig
  • 364
  • 2
  • 11
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
Kamil Naja
  • 6,267
  • 6
  • 33
  • 47