Malfy,
3 ways to get the width of a string come to mind. I'll go over those first, then how to get the length of the longest. It looks like others have addressed the regex.
1) (fastest)
If only the text itself needs to be a certain width, not the div, then you can use white-space:nowrap to ensure the text remains the full width.
$('div.someClass').css('whiteSpace','nowrap');
2) (slowest)
If you need the pixel width of a string to set another div's width, one way to do that is to create an element containing that string and use the css property above. Example:
var yourString = 'your string';
// create a div containing your string
var $tempDiv = jQuery('<div style="visibility:hidden;position:absolute;white-space:nowrap">'+jQuery.trim(yourString)+'</div>').appendTo('body');
$newDiv = <your new div, however you're creating it>;
// set the width of the new div to the width of the temp div
$newDiv.width($tempDiv.width());
// and clean up;
$tempDiv.remove();
//repeat as necessary
3) (quite fast too)
Alternately, if you're sure you'll be using a monospace font (courier, consolas, etc). There's a much faster way. Save the width of a single character and multiplying it by the length of each new text string. That way you aren't writing a new element each time. For example:
var $tempDiv = $('<div style="visibility:hidden;margin:0;padding:0;border:0;">z</div>').appendTo('body');
//(any character will work. z is just for example);
var reusableCharacterWidth=$tempDiv.width();
$tempDiv.remove();
var firstString = your string';
// set the width of your first div
$newDiv.width(reusableCharacterWidth*firstString.length);
var nextString = 'your next string';
// set the width of your next div
$nextNewDiv.width(reusableCharacterWidth*nextString.length);
(note: you may want to use $.trim() on the strings just in case)
To get the longest string:
var longestLineLength,
yourText= 'your text here';
function getLongestLineLength(lines){
var oneLineLength,
longest=0,
linesArray = lines.split('\n');
for(var i=0,len=linesArray.length;i<len;i++){
oneLineLength=linesArray[i].length;
longest=oneLineLength>longest?oneLineLength:longest;
}
return longest;
}
longestLineLength = getLongestLineLength(yourText);
Cheers!
Adam