Is there a way to specifically modify the color of the last digits in a number?

Seeking guidance on changing the color of the last digits of a number if it ends in a zero or more. For instance, transform 0.50 to 0.50, 10.00 to 10.00, 10,000.00 to 10,000.00, 100,050.00 to 100,050.00, and the like. Any assistance in achieving this would be highly appreciated.

.num{
  color: black;
  font-size: 22px;
  font-family: sans-serif;
}
<div class="num">0.50</div>
<div class="num">10.00</div>
<div class="num">10,000.00</div>
<div class="num">100,050.00</div>

Answer №1

To achieve the desired styling, you will need to perform DOM manipulation. Here is a suggested approach:

var nums = document.querySelectorAll('.num');
nums.forEach(function(n){
  var s =  n.textContent.split(/[,.0]+$/);
  var m = n.textContent.match(/[,.0]+$/);
  if(s && m && s.length > 0 && m.length > 0){
    n.innerHTML = s[0] + '<span class=numStyle>'+m[0]+'</span>';
  }
});
.num{
  color: black;
  font-size: 22px;
  font-family: sans-serif;
}
.numStyle{
  font-weight: bold;
  opacity: 0.5;
  color: red;
}
<div class="num">1.5</div>
<div class="num">0.50</div>
<div class="num">10.00</div>
<div class="num">10,000.00</div>
<div class="num">100,050.00</div>

Answer №2

USING REGEX

function highlightZeroesWithRegex(str) {
  var result = str.split(/(0(?:\n|\t|\s|0|,|\.)*)$/);
  return result[0] + `<span class="highlight">${result[1]}</span>`;
}

WITHOUT USING REGEX

  1. Identify the last sequence of repeating zeros including . and ,
  2. Enclose the zero sequence in a span element
  3. Return the modified number

Zero highlighter function

function highlightZeroesWithoutRegex(textContent) {

  let num = textContent;
  let charList = num.split('');


  let isContinuous = true;
  let nonZeroNumList = [];
  let zeroList = charList.reverse().map(num => {
      if(isContinuous && (num === '0' || num === '.' || num === ',')) {
          return num;
      } else {
          isContinuous = false;
          nonZeroNumList.push(num);
      }
  });
  let zeroNumString = zeroList.reverse().join('');
  let nonZeroNumString = nonZeroNumList.reverse().join('');

  const outputString = nonZeroNumString + `<span class="highlight">${zeroNumString}</span>`

  return outputString;
}

To iterate through all the div elements

document.querySelectorAll('.num').forEach(element => {
  element.innerHTML = highlightZeroesWithRegex(element.textContent)
})

CSS

span.highlight {
  font-weight: bolder;
}

Outputs

0.50

10.00

10,000.00

100,050.00

Demo

Answer №3

By utilizing JS and the concept of IIFE's, you can achieve the following:

(() => {
  // Access all elements with class 'num'
  const items = document.getElementsByClassName('num');
  // Loop through each item to extract its text content
  for (const item of items) {
    const length = item.innerText.length;
    const text = item.innerText;
    let digits = 0;
    // Iterate backwards, stopping at first non-zero, non-period, non-comma character
    for (var i = (length - 1); i >= 0; i--) {
        if (text[i] === '0'
        || text[i] === '.'
        || text[i] === ','
        ) {
        digits++; // Count how many characters need to be styled differently
      } else {
        break;
      }
    }
    // Modify the HTML content of each item
    // The first part displays the normal text
    // The second part highlights the characters that need styling
    item.innerHTML = `${text.substring(0, length-digits)}<b>${text.substring(length-digits, length)}</b>`
  }
})();
<div class="num">0.50</div>
<div class="num">10.00</div>
<div class="num">10,000.00</div>
<div class="num">100,050.00</div>

Answer №4

I provided two solutions utilizing the forEach() method. One involves enclosing the last character in a span tag with a specific class, while the other wraps it in a strong tag.

I made a conscious effort to avoid using variables within the loop to ensure clarity on how the code functions.

let numbers = document.querySelectorAll(".num");

numbers.forEach(function(currNum) {
    currNum.innerHTML = currNum.textContent.replace(/.$/, '<span class="last-letter">' + currNum.textContent[currNum.textContent.length - 1] + "</span>");
});
.num {
    color: black;
    font-size: 22px;
    font-family: sans-serif;
}

.last-letter {
    font-weight: bold;
    color: green;
}
<div class="num">0.50</div>
<div class="num">10.00</div>
<div class="num">10,000.00</div>
<div class="num">100,050.00</div>

This second solution does not involve a span tag with a class. Instead, the last character is enclosed in a strong tag, emphasizing its bold appearance.

let numbers = document.querySelectorAll(".num");

numbers.forEach(function(currNum) {
    currNum.innerHTML = currNum.textContent.replace(/.$/, '<strong>' + currNum.textContent[currNum.textContent.length - 1] + "</strong>");
});
.num {
    color: black;
    font-size: 22px;
    font-family: sans-serif;
}
<div class="num">0.50</div>
<div class="num">10.00</div>
<div class="num">10,000.00</div>
<div class="num">100,050.00</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to retrieve HTML code from a webpage using its URL address

Currently, I am trying to retrieve the HTML code of a specific webpage located at . My initial attempts using HttpClient were unsuccessful due to exceeding request processing time. It seems like this website may have anti-bot protection in place. I attempt ...

The wells are surpassing the line

I'm attempting to arrange 3 Wells horizontally in one row, as shown below <div class="row" style="margin-top: 10px"> <div class="span4 well"> <h3 class="centralizado"><img src="/assets/temple.png" /> & ...

Shifting a div from side to side

I don't have much experience with coding, so I was hoping for some assistance. My goal was to create a div that moves back and forth using toggleClass; $('div').on('click', function() { $(this).toggleClass('active') ...

Guide to modify target blank setting in Internet Explorer 8

<a href="brochure.pdf" target="_blank" >Click here to download the brochure as a PDF file</a> Unfortunately, using 'target blank' to open links in a new tab is not supported in Internet Explorer 8. Are there any alternative solutio ...

Having issues with my JavaScript timer - seeking assistance in troubleshooting the problem

Trying to set a timer for my little game, but facing some difficulties. The timer causes the balance to randomly increase from 0 to 13000 + some extra amount. <script> var coins = 0; var speed = 1; </script> <center> <h4> ...

Start fresh with the count for every individual table

In my HTML document, I have multiple tables with columns that have classes "valuation" and "valuation_all". If one cell in the "valuation" column contains the text "FAIL", then the corresponding cell in the "valuation_all" column should display "FAIL"; oth ...

Ensures that two divs have the same dimensions

Currently, I have a line of sections set up like this: I am attempting to ensure that the second div matches the height of the first one, despite the fact that their heights are determined by the size of the pictures which may vary. Do you have any sugges ...

Inline-block divs styled with CSS3 are causing a white gap to appear at the top of

I have been searching for solutions to my problem, but I can't seem to find one that works. My goal is to create two columns that each take up 50% of the screen width. However, I am facing an issue where there is a gap at the top that I cannot seem t ...

Constructing an HTML table with PHP echoes

I am currently developing a PHP script for tracking user attendance. The structure I am aiming for is as follows: Alternatively, you can view my jsFiddle <form action='this_page.php' method='post'> <table> <th>Me ...

Utilize CSS for Sticky Headers to Create Full Page Scrollbars for Table Control

Here is a code sandbox showcasing the use of Material UI's Table within a Paper component with a sticky header: https://codesandbox.io/s/2n40y I am looking to have the scrollbars appear at the edges of the browser page, bottom and right, while still ...

Is it frowned upon or considered incorrect to achieve a horizontally centered page by adjusting the CSS properties of the html tag?

Is it considered wrong or frowned upon to center a webpage horizontally by adjusting CSS properties of the HTML tag? Sample CSS code: <style type="text/css"> html { width: 1200px; margin: 0px auto; background-color: ...

Is utilizing the bootstrap grid system to create nested rows a viable option?

Looking to feature 1 larger image alongside 4 smaller images in a 2x2 layout: I initially considered placing everything in one row, then dividing into two columns. In the second column, I would create two rows with two columns each to achieve the desired ...

Enhancing the Appearance of MUI Date Calendar

I'm in the process of creating a calendar similar to mui's <DateCalendar />, and I want to customize the header from 'S M T W T F S' to 'Sun Mon...' as well as adjust the position of the arrows. Before: https://i.sstat ...

How to iterate and apply styles to properties of objects in an array using Vue.js?

Currently, I am working with Vue.JS and facing some challenges while outputting data using the v-for loop. My objective is to repeat a 'base' item with unique information. You can refer to the image below for better understanding. https://i.ssta ...

Adjust the size of the logo as the user scrolls

Currently, I am implementing a JavaScript feature that allows my logo to shrink when the user scrolls down and grow when they scroll up. To achieve this effect, I am utilizing the jQuery functions addClass and removeClass. However, I have encountered som ...

Show a virtual numeric keypad on the HTML input fields when they are set as type text specifically for mobile devices in a unique situation

When accessing the following web page from a mobile device, I currently have number input fields with comma separators added. However, in order to implement the comma separation function, I had to set the input type to text. This resulted in showing an alp ...

Effortless navigation through the document in both directions with seamless scrolling

To achieve a specific scrolling behavior on my webpage, I implemented the following function. Here is the code snippet: $(window).scroll(function(){ if ($(this).scrollTop() > 100) { $("html, body").animate({scrollTop: 700}, 500); re ...

Error message: Unhandled error - $(...).sidr does not exist as a function. [Chrome developer console]

I included this code in the basic module HTML block of a WordPress page builder and encountered the white screen of death. According to the Chrome developer console, the following error occurred: helpers.js?ver=4.5.3:15 Uncaught TypeError: $(...).sidr is ...

What is the smoothest way to animate price changes as you scroll?

After searching online, I could only find a version for swift. The only keyword that resulted in a search was ScrollCounter. Is it possible to create this type of animation using CSS and HTML? If anyone knows of a helpful resource or example, please share ...

Reveal and conceal using CSS animations

I am working on adding animation effects to show and hide HTML elements triggered by a button click. The button toggles a "hide" class to display or hide the element. Check out my code snippet: const toggleButton = document.querySelector('button ...