Задача: Программное создание ссылок
Исходник: программное создание ссылок, язык: javascript [code #588, hits: 11485]
автор: this [добавлен: 17.03.2009]
  1. var prototype = {};
  2. prototype.string = {};
  3.  
  4. prototype.string.autolink = function (string, options){
  5. if(!options) options = {};
  6. if(!options.limit) options.limit = 10;
  7. if(!options.tagFill) options.tagFill = '';
  8.  
  9. var regex = /((http\:\/\/|https\:\/\/|ftp\:\/\/)|(www\.))+(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi;
  10.  
  11. string = string.replace(regex, function(value){
  12. value = value.toLowerCase();
  13. var m = value.match(/^([a-z]+:\/\/)/);
  14. var nice;
  15. var url;
  16.  
  17. if(m)
  18. {
  19. nice = value.replace(m[1],'');
  20. url = value;
  21. }
  22. else
  23. {
  24. nice = value;
  25. url = 'http://' + nice;
  26. }
  27.  
  28. return '<a href="' + url + '"' + (options.tagFill != '' ? (' ' + options.tagFill) : '')+ '>' + prototype.string.autolinkLabel(nice, options.limit) + '</a>';
  29. });
  30.  
  31. return string;
  32. };
  33.  
  34.  
  35. prototype.string.autolinkLabel = function (text, limit){
  36.  
  37. if (!limit){ return text; }
  38.  
  39. if (text.length > limit){
  40. return text.substr(0, limit - 3) + '...';
  41. }
  42.  
  43. return text;
  44. };
  45.  
  46.  
  47. // Пример создания ссылок по id элемента с тектом (с применением jquery - на этапе инициализации страницы)
  48. $(function(){
  49. prototype.string.autolink($('#my-div-with-plain-text').text());
  50. });
string.autolink() - главная функция
string.autolinkLabel() - вспомогательная
Тестировалось на: IE 6.0 SP2, Mozilla FF 1.5, Opera 9.0

+добавить реализацию