DEV Community

Cover image for How to make substring bold in JSON?
Hardique Dasore
Hardique Dasore

Posted on

How to make substring bold in JSON?

We often encounter this problem where we want the substring of the description or paragraph to have a font-weight greater than the rest of the paragraph. To achieve the same, we settle for a messy inefficient code where we manually encapsulate the substring in a <strong></strong> tag.
I recently encountered a similar problem, while creating a FAQs page for a client. In one of the answers coming from JSON, the ask was to highlight certain substrings by increasing the font weight (making the string bold). For example, This is the answer to question 1.
I was not happy with the solution of creating a separate object for bold strings for each of the answers. After a few hours on the internet and multiple permutation and combinations, I finally found how to make the substring bold in the JSON itself.
We can directly encapsulate the substring we want to make bold in JSON with the <b></b> tag.

<!DOCTYPE html>
<h2>JSON with bold substring</h2>
<span id="question"></span><br/>
<span id="answer"></span>
const faq= {
 question: "Question 1", 
 answer: "This is <b>answer</b> to question 1" 
document.getElementById("question").innerHTML = faq.question;
document.getElementById("answer").innerHTML = faq.answer;
Enter fullscreen mode Exit fullscreen mode

The DOM identifies the HTML element in the JSON and increases the font weight of the substring from 300 to 600.
This hack helped me in decreasing the lines of code significantly.

Happy Coding!

Follow us on Instagram

Image description

Top comments (0)