Add line break inside string only between specific position and only if there is a white space JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We are required to write a function, say breakString() that takes in two arguments: First, the string to be broken and second, a number that represents the threshold count of characters after reaching which we have to repeatedly add line breaks in place of spaces.

For example −

The following code should push a line break at the nearest space if 4 characters have passed without a line break −

const text = 'Hey can I call you by your name?';
console.log(breakString(text, 4));

Expected Output −

Hey can
I call
you by
your
name?

So, we will iterate over the with a for loop, we will keep a count that how many characters have elapsed with inserting a ‘\n’ if the count exceeds the limit and we encounter a space we replace it with line break in the new string and reset the count to 0 otherwise we keep inserting the original string characters in the new string and keep increasing the count.

The full code for the same will be −

Example

const text = 'Hey can I call you by your name?';
const breakString = (str, limit) => {
   let brokenString = '';
   for(let i = 0, count = 0; i < str.length; i++){
      if(count >= limit && str[i] === ' '){
         count = 0;
         brokenString += '\n';
      }else{
         count++;
         brokenString += str[i];
      }
   }
   return brokenString;
}
console.log(breakString(text, 4));

Output

The console output will be −

Hey can
I call
you by
your
name?
raja
Published on 19-Aug-2020 10:21:00
Advertisements