Reputation: 198
I am inserting a <span class="subtitle">
after a comma using JavaScript and applying a few lines of CSS so that Company A, South Region reads as:
Company A,
South Region
And Company B, East Region, XYZ reads as:
Company B,
East Region, XYZ
The issue I am running into is the split on the second comma in some of the company names. I have to use <h1 class="heading">
for Company A and <h1 class="heading2">
for Company B.
The desired result is to have both use <h1 class="heading">
and somehow account for the potential of more than one comma in each company name.
$('.heading').html(function(i, html){
var html = html.split(',');
return html[0] + ',' + '<span class="subtitle">' + html[1] + '</span>'
});
$('.heading2').html(function(i, html){
var html = html.split(',');
return html[0] + ',' + '<span class="subtitle">' + html[1] + ',' + html[2] + '</span>'
});
.subtitle {
color: darkblue;
display: table;
font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="heading">Company A, South Region</h1>
<h1 class="heading2">Company B, East Region, XYZ</h1>
Upvotes: 0
Views: 87
Reputation: 34117
Try this
$("h1").removeClass("heading heading1").each(function() {
var headingHtml = $(this).html().split(',');
$(this).html("<span class='heading'>" + headingHtml[0] + "</span>");
headingHtml.shift();
$(this).append("<span class='subtitle'>" + headingHtml.join() + "</span>");
});
.subtitle {
color: darkblue;
display: table;
font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="heading">Company A, South Region</h1>
<h1 class="heading2">Company B, East Region, XYZ, ABC</h1>
Upvotes: 0
Reputation: 6316
You can use indexOf to find the first occurrence of the comma, then use slice on the string to separate from the beginning to the first occurrence of the comma, and then separate from the first coma until the end of the string, something like this:
$('.heading').html(function(i, html){
var i = html.indexOf(',');
var splits = [html.slice(0,i), html.slice(i+1)];
return splits[0] + ',' + '<span class="subtitle">' + splits[1] + '</span>'
});
.subtitle {
color: darkblue;
display: table;
font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="heading">Company A, South Region</h1>
<h1 class="heading">Company B, East Region, XYZ</h1>
Upvotes: 3