Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

80
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda