Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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(" ");

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading