I’m attempting to create a jQuery version of php’s wordwrap function — I asked an earlier question about this and was directed to this javascript function which does exactly what I’m looking for, except that I can’t get it to play friendly with jQuery — mostly I think out of ignorance.
I decided to try to adapt the code I was provided with into a jQuery plugin — for fun and because I can’t find anything to do what I want and because I figured it would be a good learning experience but I can’t get it working–
here’s the original javascript:
function wordwrap( str, width, brk, cut ) {
brk = brk || '\n';
width = width || 75;
cut = cut || false;
if (!str) { return str; }
var regex = '.{1,' +width+ '}(\\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\\S+?(\\s|$)');
return str.match( RegExp(regex, 'g') ).join( brk );
}
And then my jQuery — which I think is probably all wrong:
$.fn.wordwrap = function(options) {
var settings = $.extend({
'brk': '<br>',
'width': '5',
'cut': 'false'
}, options);
var regex = '.{1,' +settings.width+ '}(\\s|$)' + (settings.cut ? '|.{' +settings.width+ '}|.+$' : '|\\S+?(\\s|$)');
return this.html(function(i, html) {
return text.html(RegExp(regex, 'g')).join(settings.brk);
});
I have limited experience with plugin-authoring. I’ve read through the jQuery guide at http://docs.jquery.com/Plugins/Authoring and I feel like I’m doing everything properly but it doesn’t do anything when called on an element, for example:
$('#foo').wordwrap({'width' : '25'});
I’m not getting any errors on chrome web inspector but nothing happens on my page either…
I believe the problem lies in the return string at the end of the function — I am guessing that I am not doing something properly down there in order to get the desired output
Any help greatly appreciated!
UPDATE:
GOT IT THANKS!
Here’s the final script I’m using:
$.fn.wordwrap = function(options) {
var settings = $.extend({
'brk': '<br>',
'width': '75',
'cut': 'false'
}, options);
var regex = '.{1,' +settings.width+ '}(\\s|$)' + (settings.cut ? '|.{' +settings.width+ '}|.+$' : '|\\S+?(\\s|$)');
return this.html(function(i, html) {
var match = html.match(RegExp(regex, 'g'));
if (match != null) {
return match.join(settings.brk);
}
});
You don’t return text from a jQuery plugin like that, you return the collection you are working on. This makes chaining work.
I think this is what you want…
You should also change the
cutoption to default tofalse. Wrapping it in a string just makes things harder. Thewidthoption should also just be aNumber.