Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Add line break inside a string conditionally in JavaScript
In JavaScript, you can add line breaks inside a string conditionally by checking character limits and replacing spaces with newline characters. This is useful for formatting text within specific width constraints.
Problem Description
We need to create a function breakString() that takes two parameters: a string to be broken and a threshold number representing the maximum characters per line. When the character count exceeds this limit and we encounter a space, we replace it with a line break.
Algorithm Approach
The solution iterates through the string while maintaining a character count. When the count reaches the limit and we find a space, we insert a line break and reset the counter. Otherwise, we continue building the string normally.
Implementation
const text = 'Hey can I call you by your name?';
const breakString = (str, limit) => {
let brokenString = '';
for(let i = 0, count = 0; i = limit && str[i] === ' '){
count = 0;
brokenString += '
';
}else{
count++;
brokenString += str[i];
}
}
return brokenString;
}
console.log(breakString(text, 4));
Output
Hey can I call you by your name?
How It Works
The function processes each character sequentially:
- Character counting: Tracks characters since the last line break
-
Limit checking: When count reaches the threshold and finds a space, inserts
- Reset mechanism: Counter resets to 0 after each line break
- Preserve non-space characters: All other characters are added normally
Alternative with Different Limits
const longText = 'This is a longer example to demonstrate line breaking functionality';
console.log('Limit 10:');
console.log(breakString(longText, 10));
console.log('\nLimit 15:');
console.log(breakString(longText, 15));
Limit 10: This is a longer example to demonstrate line breaking functionality Limit 15: This is a longer example to demonstrate line breaking functionality
Key Points
- The function only breaks at spaces, preserving word integrity
- Character limit is a minimum threshold, not a hard maximum
- Lines may exceed the limit if no space is found at the boundary
- Empty strings and strings without spaces will not be modified
Conclusion
This approach provides a simple way to format text with conditional line breaks. The function maintains word boundaries while respecting approximate line length limits, making it ideal for text formatting applications.
