I created this function below to calculate when a string (name) reaches more than 35 characters then it break a line.
function getName(name) {
let newName = name
for (let i = 0; i < name.length; i += 1) {
if (i % 35 === 0) {
newName = `${newName.substr(0, i)}\n${newName.substr(i)}`
}
}
return newName
}
console.log(getName("Please note that popular names below"))
Eg output:
Name = "Please note that popular names below"
function output:
Please note that popular names bel
ow
What I want is to instead of break a line of these two last characters "ow", I put "below" in the next line.
If you want to break a string to certain length without cutting off any word, following code can help you:
const name = "YOUR_STRING";
const maxLen = 35; // you can play with this number to get desired result.
let result = name.substr(0, maxLen);
result = result.substr(0, Math.min(result.length, result.lastIndexOf(" ")));
So you want to find the last space within the first 35 characters and break the line there, right?
You can first slice the first 35 characters and then use regex to find the last space.
To slice the first 35 characters, use name.substr(0,35). This returns a new string with the first 35 characters.
A regular expression that matches the last space is e.g. / (?!.* )/, so you can do replace(/ (?!.* )/, x) where x is whatever you want (new line, in this case).
You can I guess keep track of the last white space index, and then when reaching 35, break the line at the white space index
function getName(name) {
let newName = name
let wsIndex = 0
for (let i = 0; i < name.length; i += 1) {
if (name.charAt(i) == ' ') wsIndex = i;
if (i % 35 === 0) {
newName = `${newName.substr(0, wsIndex)}\n${newName.substr(wsIndex+1)}`
}
}
return newName
}