I am looking for a way to insert a <br />
after only the first 4 or 5 characters in a <div>
.
Example:
<div id="wine-name">
2008 Cabernet Sauvignon</div>
To display like:
2008
Cabernet Sauvignon
Not sure which would be easier javascript or jQuery. The site is already using jQuery.
Any ideas?
The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.
You have to use <br> to have line breaks. You can replace line breaks to <br> just for display.
To create a line break in JavaScript, use “<br>”. With this, we can add more than one line break also.
The <br> tag inserts a single line break. The <br> tag is useful for writing addresses or poems.
If you are certain that you always want to insert the break after the fourth character, you can do this:
var html = $("#wine-name").html();
html = html.substring(0, 4) + "<br>" + html.substring(4);
$("#wine-name").html(html);
You can see it in action here.
If you want it to instead break after the first word (delimited by spaces), you can do this instead:
var html = $("#wine-name").html().split(" ");
html = html[0] + "<br>" + html.slice(1).join(" ");
$("#wine-name").html(html);
You can see this in action here.
EDITed for your comment:
$(".wine-name").each(function() {
var html = $(this).html().split(" ");
html = html[0] + "<br>" + html.slice(1).join(" ");
$(this).html(html);
});
See it here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With