Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

jQuery.print: pass options into print_array and print_string; use JSO…

…Ns stringify for print_string; truncate strings displayed inside arrays
  • Loading branch information...
commit 49a5ddae9985135a93659d8b2ed43ab7edad4760 1 parent 66f32f6
@tmm1 tmm1 authored
Showing with 46 additions and 13 deletions.
  1. +46 −13 lib/jquery.print.js
View
59 lib/jquery.print.js
@@ -2,12 +2,13 @@
// helper functions
- function print_array(obj){
- var max = obj.length > $.print.options.maxArray ? $.print.options.maxArray : obj.length
+ function print_array(obj, opts){
+ var max = obj.length > opts.maxArray ? opts.maxArray : obj.length
+ opts.maxString = 25
var result = [];
for (var i = 0; i < max; i++) {
- result.push($.print(obj[i]));
+ result.push($.print(obj[i], opts));
}
if (obj.length > max)
@@ -41,14 +42,46 @@
return "jQuery(length="+obj.length+")" + $.print(result)
}
- function print_string(obj){
- if (obj.length > $.print.options.maxString)
- return obj.slice(0,$.print.options.maxString) + '...'
+ function print_string(value, opts){
+ // adapted from json2.js
+ var m = { // table of character substitutions
+ '\b': '\\b',
+ '\t': '\\t',
+ '\n': '\\n',
+ '\f': '\\f',
+ '\r': '\\r',
+ '"' : '\\"',
+ '\\': '\\\\'
+ }
+
+ var r = /["\\\x00-\x1f\x7f-\x9f]/g
+
+ // If the string contains no control characters, no quote characters, and no
+ // backslash characters, then we can safely slap some quotes around it.
+ // Otherwise we must also replace the offending characters with safe sequences.
+
+ var str = r.test(value) ?
+ '"' + value.replace(r, function (a) {
+ var c = m[a];
+ if (c) {
+ return c;
+ }
+ c = a.charCodeAt();
+ return '\\u00' + Math.floor(c / 16).toString(16) +
+ (c % 16).toString(16);
+ }) + '"' :
+ '"' + value + '"';
+
+
+ if (opts.maxString && str.length > opts.maxString)
+ return str.slice(0, opts.maxString) + '..."'
else
- return obj
+ return str
}
- $.print = function(obj) {
+ $.print = function(obj, options) {
+ var opts = $.extend({}, $.print.options, options || {})
+
if (typeof obj == 'undefined')
return "undefined"
@@ -58,11 +91,14 @@
else if (!obj)
return "null"
+ else if (typeof obj == 'string')
+ return print_string(obj, opts)
+
else if ($.isFunction(obj))
return obj.toString().match(/^([^\{]*)\s{/)[1]
else if (obj instanceof Array)
- return print_array(obj)
+ return print_array(obj, opts)
else if (obj instanceof HTMLElement)
return print_element(obj)
@@ -73,15 +109,12 @@
else if (obj instanceof Object)
return print_object(obj)
- else if (typeof obj == "string")
- return print_string(obj)
-
else
return obj.toString().replace(/\n\s*/g, '')
}
$.print.options = {
maxArray: 6,
- maxString: 50
+ maxString: 0
}
})(jQuery);
Please sign in to comment.
Something went wrong with that request. Please try again.