- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add line break inside string only between specific position and only if there is a white space JavaScript
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 ‘
’ 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 += '
'; }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?
- Related Articles
- Add line break inside a string conditionally in JavaScript
- Check if a string has white space in JavaScript?
- Checking for Null or Empty or White Space Only String in Java.
- Check if the String contains only unicode letters and space in Java
- Finding the only even or the only odd number in a string of space separated numbers in JavaScript
- Check if the String has only unicode digits or space in Java
- Multiply only specific value in a JavaScript object?
- Check if the String contains only unicode letters, digits or space in Java
- How to transform two or more spaces in a string in only one space? JavaScript
- Keeping only alphanumerals in a JavaScript string in JavaScript
- Add a character to a specific position in a string using Python
- Repeating only even numbers inside an array in JavaScript
- Reversing consonants only from a string in JavaScript
- Work with white-space inside an element with CSS
- How to add horizontal borders only in specific range in Excel
