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

230
Vistas
Insert space after specific amount of numbers within a string

I got an array with a lot of strings that are badly formatted. I need to add a space to the string after the first three numbers within the String with JavaScript. The main problem is that I don't have a specific index to insert the space because the number of characters before the first three numbers vary or dont exist at all.

Example Input:

[
   "A12345678",
   "ABC12345678",
   "1234 56 7 8",
   "12 345 67 8",
   "AB12345678BVC",
]

Desired Output:

[
   "A123 45678",
   "ABC123 45678",
   "123 45678",
   "123 45678",
   "AB123 45678BVC",
]

I thought it may be solvable with replaceAll spaces to get an unbroken string and then do a for loop over each character per string and then solve this by type checking the characters to add a space at the desired position, but I get a huge amount of these arrays from the backend and it may end up in a terrible performance this way.

The other idea I got is to solve this by using Regex like in this example from a tutorial, but unfortunately I suck at writing Regex. I'd be really grateful if somebody can help me with this.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You could use String.replace() along with Array.map() to add the required space. First of all we remove all spaces from each string, then add the space at the required position.

const input = [
   "A12345678",
   "ABC12345678",
   "1234 56 7 8",
   "12 345 67 8",
   "AB12345678BVC",
]

const result = input.map(v => v.replace(/\s/g,'').replace(/(\d{3})/, '$1 '));
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

Use

const texts = [
  "A12345678",
  "ABC12345678",
  "1234 56 7 8",
  "12 345 67 8",
  "AB12345678BVC"
]
for (const text of texts) {
    console.log(text, '->', text.replace(/\s+/g,'').replace(/\d{3}(?!$)/, '$& '));
}

I.e.

  • Remove whitespaces first, then
  • Add space after first 3 digits if these digits are not at the end of the string.
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