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

108
Vistas
Javascript Modify First Word

Surely there's a better way of doing this? It's not very elegant. I'm simply wanting to make the first word bolder.

let title_array = title.split(" ");
title_array[0] = "<strong>"+title_array[0]+"</strong>";
title = title_array.join(" ");
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

I think your current approach is fine. You do have the option of using .replace() also with a regular expression:

const title = "This is a title";
const boldTitle = title.replace(/^[^\s]+/, "<strong>$&</strong>");
console.log(boldTitle);
document.body.innerHTML = boldTitle;

Here, the regular expression matches non-whitespace characters ([^\s]+) from the start of the string (^) until it reaches a whitespace character (\s). This match is then used in the replacement (referenced using $&)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Your approach is good, below is another approach using Regex

var title = "Hello to new StackOverflow";
title = title.replace(/^(\w+)/, '<strong>$1</strong>');

console.log(title);

var title = "Hello to new StackOverflow";
title = title.replace(/^(\w+)/, '<strong>$1</strong>');

console.log(title);

Since you are using React, you may have to use dangerouslySetInnerHTML to render the html.

So another approach would be something like this in React.

<div>
{
   title.split(" ").map((word, index) => {
     return index === 0 ? <strong>{word}</strong> : ` ${word}`;
  });
}
</div>
about 4 years ago · Juan Pablo Isaza Denunciar

0

I would use a CSS class. Destructuring assignment can help with defining the words, and you can use a template string to return the result.

function embolden(str) {
  const [ first, ...rest ] = str.split(' ');
  return `<span class="bold">${first}</span> ${rest.join(' ')}`;
}

const title = 'Javascript Modify First Word';
document.body.innerHTML = embolden(title);
.bold { font-weight: 700; }

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