Reputation: 3587
I have a list of numbers up to the number 10: 1,2,3,4,5,6,7,8,9,10
I need to put a zero in front of each number except the number 10.
So it looks like this: 01,02,03,04,05,06,07,08,09,10
HTML looks like this:
<p class="number weight-400">1</p>
<p class="number weight-400">2</p>
<p class="number weight-400">3</p>
<p class="number weight-400">4</p>
<p class="number weight-400">5</p>
<p class="number weight-400">6</p>
<p class="number weight-400">7</p>
<p class="number weight-400">8</p>
<p class="number weight-400">9</p>
<p class="number weight-400">10</p>
I have jquery to grab them all but I need to figure out how to add a zero to only the first 9 and not the 10th one:
$("p.number").each(function(i, index){
if (index < 10){
}
});
but my each function grabs all the <p>
and not the integer inside the p tag.
Upvotes: 1
Views: 6461
Reputation: 94101
Another option, with regex:
$('.number').text(function(i, txt) {
return txt.replace(/^\d$/, '0$&');
});
http://jsbin.com/axuyiv/1/edit
Upvotes: 5
Reputation: 94319
Here's a quick dirty way:
var num = 2;
num = (num < 10)?("0"+num):num; //"02"
Ha I tricked you. It is even not a dirty code.
Upvotes: 1
Reputation: 150050
$("p.number").text(function(i, val){
return $.trim(val).length === 1 ? '0' + val : val;
});
If you call the .text()
method on the whole collection the function you supply will be called for each item in your collection - the value you return from the function will be the new text of the current element.
Upvotes: 8