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

129
Vistas
How to insert "\n" in the second space in one string?

I want to insert \n in the second space in a string, so for example if a string has more than 1 space, it means I can add \n in the second space, if not, it means it is just one word or a string with one space and I would like to have and else where I can print it normal, so in this example, I have Hi I am here testing string, then I would like to raplace the second space with \n then it would be Hi I\nam here testing so in console it would print that string in the next way:

Hi I
am here testing

I was trying to do this with replace(/ /g,"\n") but it replaces all spaces. I hope someone could help me, thanks.

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

0

One possibility would be to use a regex to match from start of string up to the second group of spaces (1 or more) and replace that set of spaces with a newline:

const str = 'Hi I am here testing'

const regex = /^(\S+\s+\S+)\s+/

const result = str.replace(regex, '$1\n')
console.log(result)

Another possibility is to split the string on spaces and then join it back together with a newline replacing the space between the second and third word:

const str = 'Hi I am here testing'

const parts = str.split(/(\s+)/)

const result = parts.slice(0, 3).join('') + '\n' + parts.slice(4).join('')
console.log(result)

about 4 years ago · Juan Pablo Isaza Denunciar

0

you can do it with foreach in an easy way

    var myname = "alex is software engineer";
    myname = myname.split("");
    var actualString = "";
    var spaceCounter = 0;
    myname.forEach(element => {
        if(element != " ")
        {
            actualString += element;
        }
        else 
        {
            spaceCounter++;
            if(spaceCounter == 2)
            {
                actualString +="\n";
                return;
            }
            else 
            {
                actualString += " ";
            }
        }
    });
     console.log(actualString);

about 4 years ago · Juan Pablo Isaza Denunciar

0

A simple solution:

function breakLineOnSecondSpace(sentence) {
  const SPACE = ' ';
  var spaceCount = 0;
  var secondSpaceIndex = -1;

  for (var i = 0; i < sentence.length; i++) {
    var char = sentence[i];
    if (char == SPACE) spaceCount++;

    if (spaceCount === 2) {
      secondSpaceIndex = i;
      break;
    }
  }

  if (secondSpaceIndex > -1) {
    return [
      sentence.substring(0, secondSpaceIndex),
      sentence.substring(secondSpaceIndex + 1, sentence.length),
    ].join('\n');
  } else {
    return sentence;
  }
}

console.log(breakLineOnSecondSpace('Hi I am here testing'));

Working example: Stackblitz

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