rod
rod

Reputation: 309

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?

Upvotes: 12

Views: 55308

Answers (3)

raven
raven

Reputation: 43

Both the above answers have not considered the fact that the use case might include sentences where the break should be included at the nearest space prior to required limit . i.e. Above methods will break the words at specified index. But in most cases that is not the most suitable solution. Here is my take on this.

function myFunction() {
  var str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book";
   //var str = "LoremIpsumissimplydummytextoftheprintingandtypeset tingindustry.Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimensdfdfdfdfsdsds book";
  var originalStr = str;
  str = splitString(str);
  document.getElementById("demo").innerHTML = str;
}
function splitString(str)
{
    var originalStr = str;
      var charLimit = 50;
      var slicedStringList = [];
      var flag = 1;
      while(flag)
      {
        if(str.length <=50)
        {
          slicedStringList.push(str);
          flag=0;
        }
        else
        {
          var tempChar = str[charLimit]
          if(tempChar == ' ' ||tempChar == '\n' ||tempChar == '\r')
          {
            slicedStringList.push(str.substring(0,charLimit));
            str = str.substring(charLimit+1,originalStr.length);
          }
          else
          {
            var tempStr = str.substring(0,charLimit);
            var nearestSpace = tempStr.lastIndexOf(" ");
            if(nearestSpace>-1)
            {
              slicedStringList.push(str.substring(0,nearestSpace));
              str = str.substring(nearestSpace+1,originalStr.length);
            }
            else
            {
              slicedStringList.push(tempStr);
              str = str.substring(charLimit+1,originalStr.length);
            }
          }
        }
         
      }
      var newString = slicedStringList.join("<br>");
      return newString;
}
<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>

But its probably better to go with css instead.(more subtle)

Upvotes: 0

Peter Olson
Peter Olson

Reputation: 142921

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.

Upvotes: 18

Felix Glas
Felix Glas

Reputation: 15524

The code in JavaScript would look something like this:

var element = document.getElementById('wine-name');
element.innerHTML = element.innerHTML.substring(0, element.innerHTML.indexOf(' ')) + '<br />' + element.innerHTML.substring(element.innerHTML.indexOf(' '), element.innerHtml.length);

It's probably better to go with JQuery.

Upvotes: 0

Related Questions