JavaScript wordwrap
Wraps buffer to selected number of characters using string break char
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 32 33 34 3536 37 38 | function wordwrap (str, int_width, str_break, cut) { // Wraps buffer to selected number of characters using string break char // // version: 1008.1718 // discuss at: http://phpjs.org/functions/wordwrap // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // + improved by: Nick Callen // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Sakimori // + bugfixed by: Michael Grier // * example 1: wordwrap('Kevin van Zonneveld', 6, '|', true); // * returns 1: 'Kevin |van |Zonnev|eld' // * example 2: wordwrap('The quick brown fox jumped over the lazy dog.', 20, '\n'); // * returns 2: 'The quick brown fox \njumped over the lazy\n dog.' // * example 3: wordwrap('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'); // * returns 3: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod \ntempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim \nveniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea \ncommodo consequat.' // PHP Defaults var m = ((arguments.length >= 2) ? arguments[1] : 75 ); var b = ((arguments.length >= 3) ? arguments[2] : "\n" ); var c = ((arguments.length >= 4) ? arguments[3] : false); var i, j, l, s, r; str += ''; if (m < 1) { return str; } for (i = -1, l = (r = str.split(/\r\n|\n|\r/)).length; ++i < l; r[i] += s) { for (s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : "")){ j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length || c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length; } } return r.join("\n"); } |
Examples
» Example 1
Running
1 | wordwrap('Kevin van Zonneveld', 6, '|', true); |
Should return
1 | 'Kevin |van |Zonnev|eld' |
» Example 2
Running
1 | wordwrap('The quick brown fox jumped over the lazy dog.', 20, '\n'); |
Should return
1 | 'The quick brown fox \njumped over the lazy\n dog.' |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have wordwrap goodness in JavaScript.
@ Michael Grier: Great! That should obviously fix some windows issues.
@ Dave: Can you confirm that this solves your problem as well?
Without even testing in IE, I can say it should be using a regex in the split, especially when _reading_ from a textarea, because different OSes are going to be using different line break characters, and those characters are _read_ from a textarea. When you put text _into_ a textarea, the browser will insert the correct line break characters, but coming out of a textarea, the code has to deal with it.
So you should do this (windows|*nix|mac):
r = str.split(/\r\n|\n|\r/)
@ Dave + Everyone: Is there anybody out there who has IE & can confirm / debug this? Otherwise I will have to see if I can run a virtualized machine or something but that seems like a lot of trouble for one buggy function.
Slight problems using with a Textarea in IE6,7,8
In firefox the script works perfectly, just what I need. However in IE7 and IE8 if you happen to have a space at the end of the line, you get some very strange results (inserts and extra line, every character). Are you able to update your script so that if a space is at the end of the line, it deletes it(replaces with the \n). I expect it is easy to do, but I’m not a javascript expert (could do it in VBScript/ASP).
Great script though, works fine in all "proper" browsers, but unfortunately need it to work in IE as well. Thanks in advance,
Dave
@ Sakimori: Excellent points Sakimori! I've fixed all of your suggestions (even blog regex ;) Thank you!
Note that in PHP only the string parameter is required. The rest are optional.
The JS function header should just be:
[CODE="Javascript"]function wordwrap(str)[/CODE]
... and the function body should begin with:
[CODE="Javascript"] var int_width = ((arguments.length >= 2) ? arguments[1] : 75 );
var str_break = ((arguments.length >= 3) ? arguments[2] : "\n" );
var cut = ((arguments.length >= 4) ? arguments[3] : false);[/CODE]
Note that 75, new-line, and false are PHP's default values for the width, break-string, and cut flag parameters. Feel free to rewrite my code; I write for legibility, not speed.
Also of note is that the comment submission form didn't want to take my preferred email address. Looks like it doesn't like dashes in the domain name. Might want to look over your email validation regexp.
It is a great help for us familiar with php but with only little knowledge in javascript. Thank you and more power!
Keep up the work and continue creating good things like this..
I really appreciate using the wordwrap function..
Awful haha, it was a mistake in the help code, I don't check the English version of the site since I'm brazilian, I've added the missing </dd> ^^
@ Jonas Raoni: Your link gives an error in FF3 on Ubuntu:
[CODE="text"]
XML Parsing Error: mismatched tag. Expected: </dd>.
Location: http://jsfromhell.com/string/wordwrap
Line Number 135, Column 4: </dl>
----------^
[/CODE]
Be aware that the modification by Nick Callen over my original wordwrap code breaks this snippet:
alert(wordwrap("qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", 10, "\n"));
The last version is sitted here: http://jsfromhell.com/string/wordwrap
@ Andrea Giammarchi: Thanks for helping out. I wasn't mentally ready to make exceptions in my generic tester, but hey, sometimes you gotta be flexible.
I also had to change the system to accept:
[CODE="Javascript"]
define = (function(){
[/CODE]
instead of
[CODE="Javascript"]
function define(){
[/CODE]
But you'll be happy to know that it works now:
http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_define/
So thanks!
Kevin you could know PHP perfectly but you should study a bit more JavaScript :D
[CODE="Javascript"]
if(!function_exists2('define')){
document.write('<div class="bad"><xmp>n/a</xmp></div>');
outcom = ['0', 'function does not exist'];
} else {
result = (function(){
var result = false;
define('AUTHOR_NAME', 'Andrea Giammarchi');
try{result = !!AUTHOR_NAME}catch(e){};
return result;
})();
should = true;
outcom = comparer(result, should);
class = ( outcom[0] > 0 ? 'good' : 'bad' );
document.write('<div class="'+class+'"><xmp>'+print_r2(result)+'</xmp></div>');
}
[/CODE]
cya ;)
@ Andrea Giammarchi: Don't worry I think it's cool and I really want to add it. And by the way, once it's added, credits are updated automatically.
But my problem now is that I couldn't get define() compatible with my automatic tester:
http://kevin.vanzonneveld.net/pj_tester.php?unstable=true&jsfile=_define.js
So that's the reason that I had to put it 'under construction'. I have to figure out how to solve this.
I wonder why you didn't post my comment but you added "define" under construction. Come on guys, define exists and it's perfectly compatible with php one since 3 or more months ago.
Please add my name in contributes and good luck with this project.
Cheers
@ Jonas Raoni: I'm going to process all of your links (utf8 is already present though). And judging by the quality of previous functions from your hand, I think it's safe to say they'll all end up here. Thanks a bunch :)
array_diff
http://jsfromhell.com/array/diff
date
http://jsfromhell.com/geral/date-format
levenshtein
http://jsfromhell.com/string/levenshtein
bindec/decbin/dechex/etc
http://jsfromhell.com/number/base-conversor
number_format
http://jsfromhell.com/number/fmt-money
setcookie
http://jsfromhell.com/geral/cookie
utf8
http://jsfromhell.com/geral/utf-8
checkdate:
http://jsfromhell.com/geral/is-date
shuffle
http://jsfromhell.com/array/shuffle
pack/unpack
http://jsfromhell.com/classes/binary-parser
array_chunk
http://jsfromhell.com/array/chunk
array_unique
http://jsfromhell.com/array/remove-duplicated
@ mdsjack: Hi Jack, I have added include() and improved trim() to support 'nbsp'. strip_tags() was already here.
Thank you very much for contributing! Kevin
Here's some code I had done for my needs:
[CODE="Javascript"]
function include(filename) // PHP include() emulation
{ // BY mdsjack (http://www.mdsjack.bo.it)
var js = document.createElement('script');
js.setAttribute('type', 'text/javascript');
js.setAttribute('src', filename);
js.setAttribute('defer', 'defer');
document.getElementsByTagName('HEAD')[0].appendChild(js);
};
String.prototype.trim = function() // PHP trim() emulation
{ // BY mdsjack (http://www.mdsjack.bo.it)
return this.replace(/&nbsp;$/g, ' ').replace(/^\s*|\s*$/g, '');
};
String.prototype.strip_tags = function() // PHP strip_tags() emulation
{ // BY mdsjack (http://www.mdsjack.bo.it)
return this.replace(/(<([^>]+)>)/ig, '');
};
[/CODE]
cheers,
jack.


altaf
Feb 22nd