Reputation: 3978
How might I go about finding a specific character and inserting a line break using jQuery?
The character I need to find is a hyphen - and its always within a product title on an ecommerce site and takes the following format:
This is a title - This is the colour
How can I find the dash for every product title and insert a line break to for the colour name on to a separate line?
The exact HTML markup I'm using is as follows:
<a href="#" class="product c-3">
<div class="product-thumb">
<!-- Other code is in here / Removed for brevity -->
<div class="product-title">
This is a title - This is the colour
</div>
</div>
</a>
Upvotes: 2
Views: 1764
Reputation: 337560
You can use replace
to find a -
in the element's HTML and replace it with -<br />
. Try this:
$('.product-title').html(function(i, v) {
return v.replace('-', '-<br />');
});
You can replace with simply '<br />'
if you want to remove the hyphen completely.
Update: This can now be made even more succinct by using an arrow function:
$('.product-title').html((i, v) => v.replace('-', '-<br />'));
Upvotes: 8
Reputation: 66490
Try:
$('.product-title').each(function() {
var self = $(this);
self.html(self.html().replace(/-/, '-<br/>'));
});
Upvotes: 0