DEV Community

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

Posted on

4

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>
<html>
<body>
<h2>JSON with bold substring</h2>
<span id="question"></span><br/>
<span id="answer"></span>
<script>
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;
</script>
</body>
</html>


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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay