开发者

jQuery replace text using replaceText and variable

开发者 https://www.devze.com 2023-02-02 04:38 出处:网络
i tried to implement replaceText jQuery plugin from http://benalman.com/projects/jquery-replacetext-plugin/

i tried to implement replaceText jQuery plugin from http://benalman.com/projects/jquery-replacetext-plugin/

But nothing happens when the code is executed.

Thanks for any clues. Sincerely Marek

/**
 * jQuery Plugin replaceText
 **/

(function($){  
$.fn.replaceText=function(b,a,c){  
    return this.each(function(){  
        var f=this.firstChild,g,e,d=[];  
        if(f){  
            do{  
                if(f.nodeType===3){  
                    g=f.nodeValue;  
                    e=g.replace(b,a);  
                    if(e!==g){  
                        if(!c&&/</.test(e)){  
                            $(f).before(e);  
                            d.push(f)  
                        }else{  
                           开发者_Go百科 f.nodeValue=e  
                        }  
                    }  
                }  
            }while(f=f.nextSibling)  
        }  
        d.length&&$(d).remove()  
    })  
}  
})(jQuery);  

/**
 * variable containing content of q variable from google referer
 **/

var querywords = "Some+text+from+google%20referer";

/**
 * function for replace each word from body with its "marked" version
 * that is after handled by css propetry for "mark" element
 **/

$(document).ready(function ( ) {
if(window.querywords !== undefined){
    var qw = window.querywords.replace('%20','+');
    qw = qw.replace(' ','+');
    var splited = qw.split("+");
    for(var q in splited){
        $('body :not(textarea)').replaceText( /\bsplited[q]\b/gi, '<mark>$1</mark>');
    }
}
});


Instead of trying to use the variable directly in the regex like this:

$('body :not(textarea)').replaceText( /\bsplited[q]\b/gi, '<mark>$1</mark>');

You need to construct the regex from the string, like this:

$('body :not(textarea)').replaceText(new RegExp("\\b("+splited[q]+")\\b","gi"),'<mark>$1</mark>');

There are a few other issues as well, for example a for...in loop on an array, overall you want it to look like this:

$(document).ready(function ( ) {
    if(window.querywords !== undefined){
        var qw = window.querywords.replace('%20','+');
        qw = qw.replace(' ','+');
        var splited = qw.split("+");
        for(var q=0; q<splited.length; q++){
            $('body :not(textarea)').replaceText(new RegExp("\\b("+splited[q]+")\\b","gi"),'<mark>$1</mark>');
        }
    }
});

Or, a bit more compact:

$(function() {
  if(window.querywords === undefined) return;
  var qw = window.querywords.replace(/%20| /,'+').split("+");
  for(var q=0; q<qw.length; q++){
    $('body :not(textarea)').replaceText(new RegExp("\\b("+qw[q]+")\\b","gi"),'<mark>$1</mark>');
  }
});

You can test it out here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号