Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!