简体   繁体   English

JavaScript 一次替换文本中的多个字符

[英]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.因此,如果表中的值为 150%,则单元格将显示为红色。 If the value in the table is 50%, the value would be colored green.如果表中的值为 50%,则该值将显示为绿色。 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".所以,我真正处理的是“50.89%”之类的东西,到目前为止提供的解决方案将其转换为“5089”。 How can I keep the decimal?我怎样才能保留小数点?

You need to strip out all non-numeric charactes plus convert the resulating string to an int.您需要去除所有非数字字符并将结果字符串转换为 int。 So something like this: parseInt($(this).text().replace(/\D/g,'')) .所以像这样: parseInt($(this).text().replace(/\D/g,'')) Also, in your post you're comparing to a string '100' , which obviously should be a number.此外,在您的帖子中,您正在与字符串'100'进行比较,这显然应该是一个数字。 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:你可以用这个来实现,避免使用 jQuery 到 select 元素,使用纯 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.这是包含所有代码的完整提琴手

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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