rmdsf
rmdsf

Reputation: 23

how to convert only "some" of the keyword to link instead of all

ive been doing this for a week. still couldnt find the answer. i am trying to convert only some of the keyword to link instead of all. for example if theres 7 keywords in a paragraph, how can i only convert 3 of it? can someone help? please

currently this is my code.

(function($) {


       $.fn.replacetext = function(target, replacement) {
             // Get all text nodes:
             var $textNodes = this

                    .find("*")
                     .andSelf()
                     .contents()
                     .filter(function() {
                         return this.nodeType === 3 && 
                             !$(this).parent("a").length;
                     });

             $textNodes.each(function(index, element) {
                 var contents = $(element).text();
                 contents = contents.replace(target, replacement);
                 $(element).replaceWith(contents);

             });
        };
    })(jQuery);


     $("p").replacetext(/\bdress\b/gi, "<a href='http://www.google.com'>$&</a>");

Upvotes: 0

Views: 122

Answers (1)

tvanfosson
tvanfosson

Reputation: 532565

I would suggest using a limit on the function, then checking if the count of the matched item in the set of items matched so far exceeds this limit. The following will modify the first max items.

(function($) {
   $.fn.replacetext = function (target, replacement, max) {
       var limit = max || -1;

       // Get all text nodes:
       var $textNodes = this  
           .find("*")
           .andSelf()
           .contents()
           .filter(function () {
           return this.nodeType === 3 && !$(this).parent("a").length;
       });

       $textNodes.each(function (index, element) {
           var $element = $(element);
           var words = $element.text().split(/\b/);
           var matches = 0;
           var text = words.map(function (word, index) {
               if (matches >= limit) {
                   return word;
               }

               if (word.match(target)) {
                   ++matches;
                   return word.replace(target, replacement);
               }

               return word;
           });

           $element.replaceWith(text.join(''));
       });
   };
})(jQuery);

Used as

$("p").replacetext(/dress/i, "<a href='http://www.google.com'>$&</a>", 3);

In the case where you want all, simply omit the max value and it should default to all the keywords.

Upvotes: 1

Related Questions