Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

75
Views
Break line when string reaches X characters

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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(" ")));
about 4 years ago · Juan Pablo Isaza Report

0

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).

about 4 years ago · Juan Pablo Isaza Report

0

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
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!