views:

45

answers:

2

I have an array, like
var acronyms = {
'NAS': 'Nunc ac sagittis',
'MTCP': 'Morbi tempor congue porta'
};

I need to find first match of each acronym and wrap around with tag via jQuery.
E.g.
<div id="wrap">NAS dui pellentesque pretium augue. MTCP pellentesque pretium augue. NAS ac ornare lectus MTCP nec.</div>

becomes
<div id="wrap"><acronym title="Nunc ac sagittis">NAS</acronym> dui pellentesque pretium augue. <acronym title="Morbi tempor congue porta">MTCP</acronym> pellentesque pretium augue. NAS ac ornare lectus MTCP nec.</div>

Thanks.

A: 
var acronyms = {
'NAS': 'Nunc ac sagittis',
'MTCP': 'Morbi tempor congue porta'
};

content = $("#wrap").text();

$.each(acronyms, function (key, val) {
    content = content.replace(key, "<acronym title=\"" + val + "\">" + key + "</acronym>")
});

$("#wrap").html(content);
Mervyn
+2  A: 

Your array isn't actually an array. It's a javascript object. This should do it for you.

Test the live example: http://jsfiddle.net/c8tyK/

var acronyms = {
   'NAS': 'Nunc ac sagittis',
   'MTCP': 'Morbi tempor congue porta'
};

   // Get the current text in the #wrap element
var current = $('#wrap').text();

       // Iterate over the acronyms
for(var name in acronyms) {
             // Create a new regular expression from the current key
             // (You could actually skip this, and place 'name' directly
             //   in the replace() call)
    var regex = new RegExp(name);
             // Update the latest version of the current variable by doing
             //    a replace() on the first match
    current = current.replace(regex, '<acronym title="' + acronyms[name] + '">' + name + '</acronym>');
}

       // Insert the new value with HTML content
$('#wrap').html(current);
patrick dw