如何用jQuery移除逗号并为单个数字补零以修正星级评分宽度
Solution to Adjust Rating Star Widths
Got it, let's tweak your jQuery code to handle both cases properly! Your current code only strips out the comma, but we need to also append a zero after the integer part of the width value—whether there's a decimal or not.
Here's the updated code that does exactly what you need:
<script> $(document).ready(function() { $('.rating__stars').each(function() { var originalHtml = $(this).html(); // Regex to find width values and adjust them var updatedHtml = originalHtml.replace(/width:(\d+)(?:,\d+)?%/g, 'width:$10%'); $(this).html(updatedHtml); }); }); </script>
How this works:
- The regex
/width:(\d+)(?:,\d+)?%/gtargets the width values in your style attributes:width::Matches the literal start of the width property(\d+)Captures the integer part of the number (e.g.,8from8,2%or8%)(?:,\d+)?Optionally matches a comma followed by decimals (this part isn't captured, so it gets discarded entirely)%Matches the closing percentage symbol
- The replacement string
width:$10%does two things:- Takes the captured integer value (referenced as
$1) - Appends a zero and adds the percentage symbol, turning your original values into the desired
80%format
- Takes the captured integer value (referenced as
This should handle all your existing cases perfectly. If you ever have multi-digit values (like 12%), just note this would turn it into 120%—but based on your requirements, that's probably not a scenario you need to worry about right now.
内容的提问来源于stack exchange,提问作者Justus
相关产品推荐
相关产品推荐

