12

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?

Josh Darnell
  • 11,304
  • 9
  • 38
  • 66
rod
  • 309
  • 1
  • 6
  • 21

3 Answers3

18

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.

Peter Olson
  • 139,199
  • 49
  • 202
  • 242
  • Thanks, either of these work great provided there is only 1 div. In my case, a set of wines get populated in a series of li's and although each wine has a div id that = "wine-name", this only affects the first wine in the list. Strange. – rod Aug 15 '11 at 18:37
  • @Rod, you cannot have two elements with the same id. You are wanting a class. Look at my edited post to see what I mean. – Peter Olson Aug 15 '11 at 18:40
  • You're right, sorry. I added a and it worked perfectly. You rock, thanks! – rod Aug 15 '11 at 18:42
  • @M.Woodard I'm not sure what you mean. This works for any number of words. Are you asking how to break after the second word instead of the first? – Peter Olson Dec 06 '13 at 03:41
  • @PeterOlson - Yes, 2 words rather than 1 – Matthew Woodard Jan 02 '14 at 05:01
  • 1
    @MatthewWoodard Just do `html = html.slice(0,2).join("") + "
    " + html.slice(2).join("")`
    – Peter Olson Jan 02 '14 at 05:17
0

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)

raven
  • 43
  • 1
  • 7
0

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.

Felix Glas
  • 15,065
  • 7
  • 53
  • 82