SitePoint Sponsor

User Tag List

Results 1 to 14 of 14
  1. #1
    SitePoint Wizard bronze trophy PicnicTutorials's Avatar
    Join Date
    Dec 2007
    Location
    Carlsbad, California, United States
    Posts
    3,658
    Mentioned
    15 Post(s)
    Tagged
    0 Thread(s)

    How to use JS to insert line break into html?

    How to use JS to insert line break at a specific character length into the html? Not into the JS itself (i.e. \n), but to break a long string of text? This code was presented over in the CSS forum, however, I can't get it to work. Do you see what it may be missing? Thanks!
    Code:
    function word_break(source, length)
    {
        if ( length > 0 )
        {
            var i = length;
            while ( i < source.length() )
            {
                   source = source.substr(0,i) + "<br />" + source.substr(i);
                   i = i + length;
            }
     
        }
    }

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you have a string that needs more than a single break you will need a new variable to hold the string you are building,
    so you do not lose the source on the first iteration of your loop.

    substr will not work correctly after the first iteration- use substring instead.

    If you are only cutting a string into two parts, don't use a loop at all.

  3. #3
    SitePoint Wizard bronze trophy PicnicTutorials's Avatar
    Join Date
    Dec 2007
    Location
    Carlsbad, California, United States
    Posts
    3,658
    Mentioned
    15 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by mrhoo View Post
    You need a new variable to hold the string you are building,
    so you do not lose the source on the first iteration of your loop.
    Hi, mind showing me how to do that?

  4. #4
    Function Curry'er JimmyP's Avatar
    Join Date
    Aug 2007
    Location
    Brighton, UK
    Posts
    2,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code JavaScript:
    String.prototype.breakAt = function(breakAt) {
        return this.substr(0,breakAt) + '<br/>' + this.substr(breakAt);
    };
     
    var testString = 'This is a test string';
     
    testString.breakAt(4); // = This<br/> is a test string
    James Padolsey
    末末末末末末末末末末末末末末末末末末末
    Awesome JavaScript Zoomer (demo here)
    'Ajaxy' - Ajax integration solution (demo here)

  5. #5
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You may want to think of breaking lines on spaces, or hyphenating long words.

    This method can take up to 3 arguments.
    The first is the maximum line length,
    the second is the minimum length of a hyphenated word,
    the third is a switch for the line break string.

    elem.innerHTML= s.wrap(20, 10, true);

    Code:
    String.prototype.wrap= function(n, hyphen, br){
    	var str1, tem, ax, diff, lim, S= [];
    	var A= this.split(/\s*\n/);
    	n= n || 50;
    	hyphen= hyphen || n*2;
    	hyphen= Math.floor(hyphen/2);
    	while(A.length){
    		str1= A.shift();
    		while(str1 && str1.length> n){
    			if(ax=== 0 && /^\S/.test(str1)) S[S.length-1]+= '-';
    			tem= str1.substring(0, n);
    			ax= tem.lastIndexOf(' ')+ 1;
    			if(ax== 0){
    				S.push(str1.substring(0, n-1));
    				str1= str1.substring(n-1);
    			}
    			else{
    				tem= str1.substring(0, ax);
    				diff= n-ax;
    				if(diff> hyphen){
    					lim=ax+ hyphen;
    					while(ax<lim && /\w/.test(str1.charAt(ax))) ++ax;
    					tem= str1.substring(0, ax)+'-';
    				}
    				str1= str1.substring(ax);
    				S.push(tem);
    			}
    		}
    		if(str1) S.push(str1);
    	}
    	br= br? '<br>\n': '\n';
    	return S.join(br);
    }
    //test:
    var s= "This is a test of the American Broadcast System. This is only a test, and not an actual emergency situation. If it was an actual emergency situation, we wouldn't have said it was only a test.";


    s.wrap(20) returns>>

    This is a test of
    the American
    Broadcast System.
    This is only a
    test, and not an
    actual emergency
    situation. If it
    was an actual
    emergency
    situation, we
    wouldn't have said
    it was only a test.

    s.wrap(20,10,true) returns>>

    This is a test of <br>
    the American Broad-<br>
    cast System. This <br>
    is only a test, and <br>
    not an actual emerg-<br>
    ency situation. If <br>
    it was an actual <br>
    emergency situa-<br>
    tion, we wouldn't <br>
    have said it was <br>
    only a test.
    Last edited by mrhoo; Nov 27, 2008 at 17:19.

  6. #6
    SitePoint Wizard bronze trophy PicnicTutorials's Avatar
    Join Date
    Dec 2007
    Location
    Carlsbad, California, United States
    Posts
    3,658
    Mentioned
    15 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by JimmyP View Post
    Code JavaScript:
    String.prototype.breakAt = function(breakAt) {
        return this.substr(0,breakAt) + '<br/>' + this.substr(breakAt);
    };
     
    var testString = 'This is a test string';
     
    testString.breakAt(4); // = This<br/> is a test string
    Very cool! Thanks guys! A couple questions though? I'm still a little slow with "anything JS". Jimmy, I thought I'd just wrap that all in a inline JS script tags and that would be it. But it just comes up blank for me. What ingredient am I missing?

    You may want to think of breaking lines on spaces, or hyphenating long words.

    This method can take up to 3 arguments.
    The first is the maximum line length,
    the second is the minimum length of a hyphenated word,
    the third is a switch for the line break string.

    elem.innerHTML= s.wrap(20, 10, true);

    Code:
    String.prototype.wrap= function(n, hyphen, br){
    	var str1, tem, ax, diff, lim, S= [];
    	var A= this.split(/\s*\n/);
    	n= n || 50;
    	hyphen= hyphen || n*2;
    	hyphen= Math.floor(hyphen/2);
    	while(A.length){
    		str1= A.shift();
    		while(str1 && str1.length> n){
    			if(ax=== 0 && /^\S/.test(str1)) S[S.length-1]+= '-';
    			tem= str1.substring(0, n);
    			ax= tem.lastIndexOf(' ')+ 1;
    			if(ax== 0){
    				S.push(str1.substring(0, n-1));
    				str1= str1.substring(n-1);
    			}
    			else{
    				tem= str1.substring(0, ax);
    				diff= n-ax;
    				if(diff> hyphen){
    					lim=ax+ hyphen;
    					while(ax<lim && /\w/.test(str1.charAt(ax))) ++ax;
    					tem= str1.substring(0, ax)+'-';
    				}
    				str1= str1.substring(ax);
    				S.push(tem);
    			}
    		}
    		if(str1) S.push(str1);
    	}
    	br= br? '<br>\n': '\n';
    	return S.join(br);
    }
    mrhoo, pretty much the same question for you as well. And, were does this part go? elem.innerHTML= s.wrap(20, 10, true);

    Thanks for help guys!

  7. #7
    SitePoint Wizard bronze trophy PicnicTutorials's Avatar
    Join Date
    Dec 2007
    Location
    Carlsbad, California, United States
    Posts
    3,658
    Mentioned
    15 Post(s)
    Tagged
    0 Thread(s)
    Bump

    If someone could give me just a little explanation on how to place each, that would be awesome! Like take yours for instance Jimmy. I just thought I wrap it in script tags and place it in the html - does not work though - comes up blank. Do I need the prototype library also for this to work?

    <script type="text/javascript">
    String.prototype.breakAt = function(breakAt) {
    return this.substr(0,breakAt) + '<br/>' + this.substr(breakAt);
    };

    var testString = 'This is a test string';

    testString.breakAt(4); // = This<br/> is a test string
    </script>

  8. #8
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    No, the prototype library has nothing to do with this. The prototype property is completely different, in that it's built in to javascript and provides you access to the owner object, allowing you to make changes to it that affect all objects related to the owner.

    In the above case, all strings will have an additional method called breakAt which you can use.

    The above code doesn't appear to do anything when run on a page because it just changes the contents of a variable called testString. you would need to alert that variable or display it on the page in some way to see the end result.

    See https://developer.mozilla.org/en/Cor...ring/prototype for more about prototype and the String object.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  9. #9
    SitePoint Wizard bronze trophy PicnicTutorials's Avatar
    Join Date
    Dec 2007
    Location
    Carlsbad, California, United States
    Posts
    3,658
    Mentioned
    15 Post(s)
    Tagged
    0 Thread(s)
    Thanks for your reply. Unfortunately though, that link does not get me any closer to getting either of the above scripts to work. Anybody? Thanks!

  10. #10
    SitePoint Enthusiast
    Join Date
    Aug 2008
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    document.write(testString.breakAt(4));

  11. #11
    SitePoint Member
    Join Date
    Dec 2008
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here's a more concise algo. Written in VB but the same methods exist in JS

    Code:
      Private Function GridTextWrap(ByVal str As String, ByVal len As Integer) As String
        Try
          Dim temp As String() = str.Split(" ")
          Dim res As String = ""
          Dim index As Integer = 1
          For Each s In temp
            If res.Length + s.Length > (index * len) Then
              res = res + "<br>"
              index += 1
            End If
            res = res + IIf(res.Length <> 0, " ", "") + temp(index)
          Next
          Return res
        Catch ex As Exception
          Return str
        End Try
      End Function
    Quote Originally Posted by mrhoo View Post
    You may want to think of breaking lines on spaces, or hyphenating long words.

    This method can take up to 3 arguments.
    The first is the maximum line length,
    the second is the minimum length of a hyphenated word,
    the third is a switch for the line break string.

    elem.innerHTML= s.wrap(20, 10, true);

    Code:
    String.prototype.wrap= function(n, hyphen, br){
    	var str1, tem, ax, diff, lim, S= [];
    	var A= this.split(/\s*\n/);
    	n= n || 50;
    	hyphen= hyphen || n*2;
    	hyphen= Math.floor(hyphen/2);
    	while(A.length){
    		str1= A.shift();
    		while(str1 && str1.length> n){
    			if(ax=== 0 && /^\S/.test(str1)) S[S.length-1]+= '-';
    			tem= str1.substring(0, n);
    			ax= tem.lastIndexOf(' ')+ 1;
    			if(ax== 0){
    				S.push(str1.substring(0, n-1));
    				str1= str1.substring(n-1);
    			}
    			else{
    				tem= str1.substring(0, ax);
    				diff= n-ax;
    				if(diff> hyphen){
    					lim=ax+ hyphen;
    					while(ax<lim && /\w/.test(str1.charAt(ax))) ++ax;
    					tem= str1.substring(0, ax)+'-';
    				}
    				str1= str1.substring(ax);
    				S.push(tem);
    			}
    		}
    		if(str1) S.push(str1);
    	}
    	br= br? '<br>\n': '\n';
    	return S.join(br);
    }
    //test:
    var s= "This is a test of the American Broadcast System. This is only a test, and not an actual emergency situation. If it was an actual emergency situation, we wouldn't have said it was only a test.";


    s.wrap(20) returns>>

    This is a test of
    the American
    Broadcast System.
    This is only a
    test, and not an
    actual emergency
    situation. If it
    was an actual
    emergency
    situation, we
    wouldn't have said
    it was only a test.

    s.wrap(20,10,true) returns>>

    This is a test of <br>
    the American Broad-<br>
    cast System. This <br>
    is only a test, and <br>
    not an actual emerg-<br>
    ency situation. If <br>
    it was an actual <br>
    emergency situa-<br>
    tion, we wouldn't <br>
    have said it was <br>
    only a test.
    Last edited by hypoxide; Dec 12, 2008 at 09:32.

  12. #12
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    I think you're just looking for how to actually use it with some HTML. Let's say you have a paragraph:
    HTML Code:
    <p id="cholera">President Robert Mugabe has said Zimbabwe has contained cholera - as the UN and a UK charity warned the deadly outbreak was getting worse. Save the Children said: "If anything is certain in the chaos of Zimbabwe today it is that the cholera outbreak is not under control." Mr Mugabe also said Western powers were plotting to use cholera as an excuse to invade and overthrow him. "Now that there is no cholera there is no cause for war," he said.</p>
    Then in your javascript (using what JimmyP posted):
    Code javascript:
    var cholera = document.getElementById('cholera');
    cholera.innerHTML = cholera.innerHTML.breakAt(60);
    In the case of mrhoo's more flexible and complete solution:
    Code javascript:
    var cholera = document.getElementById('cholera');
    cholera.innerHTML = cholera.innerHTML.wrap(60, 10, true);
    All of this would preferably go in an external javascript file, which you can then reference using a <script> element just before the closing </body> tag.

  13. #13
    SitePoint Wizard bronze trophy PicnicTutorials's Avatar
    Join Date
    Dec 2007
    Location
    Carlsbad, California, United States
    Posts
    3,658
    Mentioned
    15 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Raffles View Post
    I think you're just looking for how to actually use it with some HTML. Let's say you have a paragraph:
    HTML Code:
    <p id="cholera">President Robert Mugabe has said Zimbabwe has contained cholera - as the UN and a UK charity warned the deadly outbreak was getting worse. Save the Children said: "If anything is certain in the chaos of Zimbabwe today it is that the cholera outbreak is not under control." Mr Mugabe also said Western powers were plotting to use cholera as an excuse to invade and overthrow him. "Now that there is no cholera there is no cause for war," he said.</p>
    Then in your javascript (using what JimmyP posted):
    Code javascript:
    var cholera = document.getElementById('cholera');
    cholera.innerHTML = cholera.innerHTML.breakAt(60);
    In the case of mrhoo's more flexible and complete solution:
    Code javascript:
    var cholera = document.getElementById('cholera');
    cholera.innerHTML = cholera.innerHTML.wrap(60, 10, true);
    All of this would preferably go in an external javascript file, which you can then reference using a <script> element just before the closing </body> tag.
    Awesome! Thank you very much Raffles for putting it in terms that I could understand. I was able to make them both work. Have a good one!

  14. #14
    Non-Member
    Join Date
    Jun 2008
    Posts
    159
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Raffles I was looking for a solution like this for ages too


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •