How to Bold Text in JavaScript – Don’t Use String.bold()!

If you are wondering how to bold text in JavaScript, you might have come across other articles telling you to use the String.prototype.bold() method. Don’t do this!

There are two primary reasons:

  1. String.prototype.bold() is deprecated and could be removed in the future at any time.
  2. It works by wrapping the string in <b> tags which is no longer recommended. Instead, bold text should be represented in JavaScript with <strong> tags.

Here is a function you can use to bold text in JavaScript:

function boldText(str) { return `<strong>${str}</strong>`; }
Code language: JavaScript (javascript)

Note that the string must then be inserted into the HTML for it to actually appear bolded. Check out the demo below for an example.

Demo

Here is a demo showing how you could use the boldText function:

// Get the <div> element const div = document.querySelector('#my-div'); // Create the text to insert const text = 'Hello, world!'; // Bold the text using the boldText() function const boldText = boldText(text); // Insert the bold text into the <div> element div.innerHTML = boldText;
Code language: JavaScript (javascript)

Alternative Methods

If you have an element already on the page that you would like to bold, then the easiest way would be to change the CSS of that element to add the font-weight: bold property.

Here is an example:

const paragraph = document.querySelector('#my-paragraph'); paragraph.style.fontWeight = 'bold';
Code language: JavaScript (javascript)

Alternatively, you can use the element.classList property to add a CSS class that defines the font-weight property. This allows you to separate your CSS styles from your JavaScript code and makes it easier to reuse your styles.

For example, if you have a CSS class called bold that sets the font-weight property to bold, you could use the following code to apply the class to the paragraph element:

paragraph.classList.add('bold');
Code language: JavaScript (javascript)

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *