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.
), 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!


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;
        }
 
    }
}

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.

Hi, mind showing me how to do that?


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

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);

String.prototype.wrap= function(n, hyphen, br){
	var str1, tem, ax, diff, lim, S= [];
	var A= this.split(/\\s*\
/);
	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>\
': '\
';
	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.

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);

String.prototype.wrap= function(n, hyphen, br){
	var str1, tem, ax, diff, lim, S= [];
	var A= this.split(/\\s*\
/);
	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>\
': '\
';
	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!

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>

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/Core_JavaScript_1.5_Reference/Global_Objects/String/prototype for more about prototype and the String object.

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!

document.write(testString.breakAt(4));

Here’s a more concise algo. Written in VB but the same methods exist in JS

  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

I think you’re just looking for how to actually use it with some HTML. Let’s say you have a paragraph:

<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):

var cholera = document.getElementById('cholera');
cholera.innerHTML = cholera.innerHTML.breakAt(60);

In the case of mrhoo’s more flexible and complete solution:

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! :slight_smile:

Thanks Raffles I was looking for a solution like this for ages too