यूआरएल छंटनी के लिए मैं बीच में छोटा करना चुनता हूं, क्योंकि डोमेन और फ़ाइल आमतौर पर निर्देशिका पथ से अधिक महत्वपूर्ण होती है।
एंड्रयू प्लमर की जावास्क्रिप्ट लाइब्रेरी Sugar के GitHub fork से इस प्रश्न के लिए लिया गया और अनुकूलित किया गया।
var toShorten = 'http://stackoverflow.com/questions/9156458/when-using-jquery-linkify-plugin-how-do-i-truncate-the-url';
var shortened = toShorten.shorten(20); // Output: 'http://st...-the-url'
नोट::
String.prototype.shorten = function(length, position, countSplitter, splitter) {
if (this.length < 1 && length < 1) return String(this);
if (!(typeof(splitter) === 'string')) splitter = '...';
if (!(typeof(countSplitter) === 'boolean')) countSplitter = true;
var balance = (countSplitter) ? splitter.length : 0;
if (length <= balance || this.length <= length) return String(this);
// Perform shortening
var shortened, beforeSplitter, afterSplitter;
if (position == 'left') {
afterSplitter = this.substring(this.length - length + balance, this.length - 1);
shortened = splitter + afterSplitter;
} else if (position == 'right') {
beforeSplitter = this.substring(0, length - balance);
shortened = beforeSplitter + splitter;
} else {
beforeSplitter = this.substring(0, Math.ceil((length/2) - (balance/2)));
afterSplitter = this.substring(this.length - Math.floor((length/2) - (balance/2)), this.length);
shortened = beforeSplitter + splitter + afterSplitter;
}
return shortened;
}
तो उसके एवज में स्ट्रिंग एक यूआरएल को छोटा करने का उदाहरण 20 वर्ण लंबा है इस कोड को केवल सबूत पढ़ने और नहीं इकाई का परीक्षण किया गया है। Sugar implementation हालांकि, unit tested रहा है।
स्रोत
2012-02-09 15:48:50
यदि आप लिंक काट लेंगे तो यह एक लिंक के रूप में बेकार होगा लेकिन यदि आप इसे इस तरह प्रदर्शित करना चाहते हैं तो आप इसे लागू करने के लिए कुछ अन्य jQuery प्लगइन को कार्यान्वित कर सकते हैं। – NAVEED