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

What does .replace(/^[^:]+:/, '<b>$&</b>') mean in javascript

So I wanted a code to make my HTML list to be bold before a colon. So I searched for a code that I chould use. And saw one code in stack overflow: https://stackoverflow.com/a/46855744/15163136. Instead of using a for loop I used a foreach loop.

<ul>
 <li>Apple: Has the color red</li>
 <li>Orange: Has the color orange</li>
 <li>Banana: Has the color yellow</li>
 <li>Blackberries: Has the color purple</li>
 <li>Avocado: Has the color green</li>
</ul>

 <script type="text/javascript">

   let list = document.querySelectorAll("ul li");
   list.forEach((element) => {
     element.innerHTML = element.innerText.replace(/^[^:]+:/, '<b>$&</b>');
     
 </script>

But the only thing is that I don’t understand the /^[^:]+:/ and '<b>$&</b>'
What does this mean?

Thank you in advance!

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

>Solution :

/^[^:]+:/ it match any characters from the start of string till first match of : replace it with itself($&) but surrounded by
<b> tag to make it bold

"<li>Apple: Has the color red</li>".replace(/^[^:]+:/, '<b>$&</b>');

result <li><b>Apple:</b> Has the color red</li>

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