
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 a String Conditionally in JavaScript
We are required to write a function breakString() that takes in two arguments first the string to be broken and second is a number that represents the threshold count of characters after reaching which we have to repeatedly add line breaks in place of spaces.
So, let’s do it. 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 −
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));
Following is the console output −
Hey can I call you by your name?
Advertisements