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

Time:12-13

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!

CodePudding user response:

/^[^:] :/ 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>

CodePudding user response:

/^[^:] :/ and <b>$&</b> The first part is a regular expression. You can see regular expressions often wrapped in / /. Regular expressions describe patterns to be matched inside a string. Different symbols mean different things depending on the context.

If a regular expression starts with a ^ this means that the pattern has to match from the start of the string.

Next we have the [^:] . The square brackets describe characters we are looking for. So [a-z] would mean match every lower case character. Here instead of a-z, we have ^:. Inside the character brackets, ^ means not, so [^:] means find any character that is not a colon. A after finding something means find 1 or more of these. So, [^:] means find 1 or more characters that are not :.

Next we have a :, which means find a colon. So, to read the whole regular expression, /^[^:] :/ - from the start of the string find every character that is not a colon, then find a colon. If it finds this, it is considered a match.

The <b>$&</b> describes what to do with the match. If you wrote in this second argument Item - , then every line would get rid of the fruit name and replace it like this Item - Has the color red. Here $& means 'use the thing we matched'. So this takes the whole match and wraps it in <b>..</b>, making it bold.

  • Related