Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery or javascript to add one line break <br /> after x amount of characters in a <div>

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?

like image 346
rod Avatar asked Aug 15 '11 18:08

rod


People also ask

How do you insert a line break in JavaScript?

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.

How do you add a new line in jquery?

You have to use <br> to have line breaks. You can replace line breaks to <br> just for display.

How do you create a break in JavaScript?

To create a line break in JavaScript, use “<br>”. With this, we can add more than one line break also.

What is break tag in JavaScript?

The <br> tag inserts a single line break. The <br> tag is useful for writing addresses or poems.


1 Answers

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.

like image 86
Peter Olson Avatar answered Oct 23 '22 12:10

Peter Olson