skip to Main Content

I have one string

string = "example string is cool and you're great for helping out A string is a sequence of characters"  

I want to insert a line break every words in array so it returns this:

const cars = [" is cool", "great for", "out"];
string = 'example string n 
is cooln 
and you'ren 
great forn
helpingn
outn
A string is a sequence of characters'

I am working with variables and cannot manually do this. I need a function that can take this string and handle it for me. and Between two array words is a newline

Thanks!!

2

Answers


  1. You can try the following function:

    function insertLineBreaks(string) {
      const words = string.split(' '); // Split the string into an array of words
      const breaks = [];
    
      for (let i = 0; i < words.length - 1; i++) {
        breaks.push(words[i] + ' ' + words[i + 1]); // Combine each pair of consecutive words with a space
      }
    
      return breaks.join('n'); // Join the array with line breaks
    }
    
    Login or Signup to reply.
  2. Use str_replace()

    $subject = "example string is cool and you're great for helping out A string is a sequence of characters";
    $search = [" is cool", "great for", "out"];
    
    $replace = array_map(fn ($s) => "$sn", $search);
    
    print_r(str_replace($search, $replace, $subject));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search