2010-06-16 7 views
2

J'ai un tableau, comme
var acronyms = {
'NAS': 'Nunc ac sagittis',
'MTCP': 'Morbi tempor congue porta'
};
jQuery remplacer premier match string

Je dois trouver le premier match de chaque acronyme et enrouler autour avec étiquette via jQuery.
E.g.
<div id="wrap">NAS dui pellentesque pretium augue. MTCP pellentesque pretium augue. NAS ac ornare lectus MTCP nec.</div>

devient
<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>

Merci.

Répondre

3

Votre tableau n'est pas réellement un tableau. C'est un objet javascript. Cela devrait le faire pour vous.

Testez l'exemple en direct: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); 
0
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); 
Questions connexes