Im trying to construct a bookmarklet that add some elements inside a text following a dictionary (a parsed json).
For this I used a regex object and a replace method to add the new elements but it is not adding something. In various stages of the script Im seeing if it is working or not (debugging through console in firebug) so Im seeing that everything is working except the replace.
This is the code:
jj = jQuery.noConflict()
jj ->
escapedStr = (string)->
string.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1")
addTags = (pjson) ->
for i in [0...jj(".postauthor").length]
name = jj(".postauthor").eq(i).text()
if pjson.hasOwnProperty(name)
texto = jj(".postauthor").eq(i).parent().next().find(".postbody:first").text()
for x in pjson[name]
escCon = escapedStr x['concept']
#console.log escCon
change = new RegExp(escCon, "ig")
texto.replace(change, "<span class='concept'>#{escCon}</span>")
jj.ajax({
crossOrigin: true
url: "/something.json"
datatype: "json"
success: (data) ->
addTags jj.parseJSON(data)
})
The code of the bookmarklet is something like this:
if (!($ = window.jQuery)) {
script = document.createElement( 'script' );
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
script.onload=releasetheKraken;
document.body.appendChild(script);
}
else {
releasetheKraken();
}
function releasetheKraken() {
var jsCode = document.createElement('script');
jsCode.setAttribute('src', 'https://something/above_code.js');
document.body.appendChild(jsCode);
}
Everything is working but last replace in the function addTags
. Im newby so I dont know if what Im trying is possible to do or not. Can you let me some advice? Thank you in advance.
Finally I solved the question but I dont exactly why my first approach doesnt work.
What I did was chain some .html() methods that injected the desired elements... something like replacing the whole big parent element by the edited one:
texto.html(texto.html().replace(change,"<span class='concept'>#{x['concept']}</span>"))
It seems like the replace, in the code that open this question, just is replacing things in memory but it is not injecting anything in the real HTML.