Reputation: 1790
I know this has been asked before but I couldn't find the right answer to my specific question. I'd like to add whitespace between lowercase and uppercase, only in divs with specific class.
Let's say I have this html:
<div class='type'>CreditCard</div>
<div class='type'>DebitCard</div>
I'd like this to be:
<div class='type'>Credit Card</div>
<div class='type'>Debit Card</div>
using this code:
$('.type').html($('.type').html().replace(/([a-z])([A-Z])/g, "$1 $2"));
results in:
<div class='type'>Credit Card</div>
<div class='type'>Credit Card</div>
See also https://jsfiddle.net/ny8h5rv4/
What am I doing wrong? Assuming I don't know the content of the div (credit card and debit card just being an example)
$('.type').html($('.type').html().replace(/([a-z])([A-Z])/g, "$1 $2"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='type'>CreditCard</div>
<div class='type'>DebitCard</div>
Upvotes: 1
Views: 125
Reputation: 207511
Problem with your code is html() only returns it to the first element in the collection. You than apply it to all the elements in the collection. You need to loop over the collection. So you can use each() or you can use a function inside of html()/text(). The method arguments are index and the text/html. You return the string you want to apply for that index.
$(".type").text(
function(index, txt) {
return txt.replace(/([a-z])([A-Z])/g, "$1 $2");
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='type'>CreditCard</div>
<div class='type'>DebitCard</div>
Upvotes: 1
Reputation: 1249
You should add a for loop.
$('.type').html()
just get first element's html and apply to all $('.type')
.
$('.type').each(function(elem) {
$(this).html($(this).html().replace(/([a-z])([A-Z])/g, "$1 $2"));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='type'>CreditCard</div>
<div class='type'>DebitCard</div>
Upvotes: 2