Reputation: 40651
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{
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>');
}
}
});
Upvotes: 0
Views: 1970
Reputation: 630469
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>');
}
});
Upvotes: 2