Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

111
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda