Reputation: 21
I'm trying to wrap a span around the first part of a plain text in a div and style it with a different font-color and font size and have a line-break after it. The problem is, that it's a plain text in which I can't add any custom code in the backend, so I have to find a trick to do the job.
It's a plain text input field in a CMS and this is the result in the frontend:
Next date: 12.09.-25.09.2019. In this course you can learn how to...
It's the date-part, which I want to highlight...
Now I have several ideas to do the trick:
[Next date: 12.09.-25.09.2019] In this course you can learn how to...
So everything in between the brackets should be red for example
Next date: 12.09.-25.09.2019 ### In this course you can learn how to...
... and tell jquery to find everything before the ### and wrap a span around. The ### should disappear of course, when their job is done :-)
Important to know... there will be multiple different dates on one site, so maybe the third solution would work best, so I could parse the entire site and search for the ### to edit everything that's before it, in every instance... so it wouldn't matter what it says before those hashtags... it would also be nice to add a line-break after the ### so that the following text starts in a new line...
this is the given code:
<div id="cc-m-1" class="j-module n j-text ">
Next date: 12.09.-25.09.2019 In this course you can learn how to...
</div>
<div id="cc-m-1" class="j-module n j-text ">
Next date: 26.09.-05.10.2019 This is another course for you...
</div>
Hope you get the idea, and someone can assist me, thanks in advance!
Upvotes: 2
Views: 490
Reputation: 1206
Without a better sample of your data, it's tough to handle all the quirks, but this should get you started. Good luck!
$(document).ready(function() {
$(".j-module").each(function() {
styleDiv($(this).attr("id"));
});
});
function isDate(dt) {
var date = new Date(dt.replace(".", "-"));
return (date instanceof Date);
}
function styleDiv(id) {
var alltext = $("#" + id);
var chunks = new Array();
chunks = $("#" + id).text().split(" ");
var texttobold = "";
for (var i = 0; i < chunks.length; i++) {
var dateFinder = chunks[i];
texttobold = texttobold += " " + dateFinder;
if (dateFinder.length == 10 && isDate(dateFinder)) {
var outpt = "<span class='boldtext'>" + texttobold + "</span>";
alltext.html(alltext.text().replace(texttobold.trim(), outpt));
}
}
}
.boldtext {
font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="cc-m-1" class="j-module n j-text">
Next date: 25.09.2019 In this course you can learn how to...
</div>
<div id="cc-m-2" class="j-module n j-text">
Your favorite date: 21.12.2020 In this course you can learn how to...
</div>
<div id="cc-m-3" class="j-module n j-text">
Next date: 04.09.2019 In this course you can learn how to...
</div>
Edited to expand the required range of text to style.
Upvotes: 1