简体   繁体   中英

JavaScript Replace Multiple Characters in Text at Once

I have a table that I'm trying to color based on the values in the table. So, if the value in the table is 150%, the cell would be colored red. If the value in the table is 50%, the value would be colored green. However, for some reason, the actual text in the table has a multitude of spaces within them as well as a % symbol. How can I replace any spaces and '%' characters with nothing ('')?

Here is what I have that isn't working:

<script type="text/javascript">

        $(document).ready(function () {
            $('#myTable td.PercentMem').each(function () {
                if ($(this).text().replace(/\s/g, '').replace('%', '') >= '100') {
                    $(this).css('background-color', '#ff0000');
                }
                else {
                    $(this).css('background-color', '#33cc33');
                }
            });
        });

    </script>

Thank you!

EDIT

I'm dumb. I forgot to include the fact that these percentages have a decimal point in them. So, what I'm really dealing with is something like "50.89%", and the solutions provided thus far convert that into "5089". How can I keep the decimal?

You need to strip out all non-numeric charactes plus convert the resulating string to an int. So something like this: parseInt($(this).text().replace(/\D/g,'')) . Also, in your post you're comparing to a string '100' , which obviously should be a number. Try this:

        $(document).ready(function () {
            $('#myTable td.PercentMem').each(function () {
                if (parseInt($(this).text().replace(/\D/g,'')) >= 100) {
                    $(this).css('background-color', '#ff0000');
                }
                else {
                    $(this).css('background-color', '#33cc33');
                }
            });
        });

Disclaimer: I have not actually tested this, but this should work.

You can achieve with this, avoid to use jQuery to select elements, use pure JavaScript:

const myCells = document.querySelectorAll('.PercentMem');

myCells.forEach(cell => {
  const cellValue = cell.textContent.replace(/\D+/g, '');
        
  cell.classList.toggle(parseInt(cellValue) >= 100 ? 'red' : 'green');
});

Here is the complete fiddler with all the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM