I'm trying to use JavaScript to replace target text with a hyperlinked version of the target text. Generally speaking, this is the function in question:
function replace_text_in_editor(target_text, target_type, target_slug) {
//if target_text was "Google", then the replacement_text might be "<a href="/path/to/google">Google</a>
var replacement_text = get_replacement_text(target_text, target_type, target_slug);
if(typeof replacement_text != undefined && replacement_text != '') {
var content = '';
content = jQuery( "#content" ).val();
content = content.replace(target_text,replacement_text)
if(content != '') {
jQuery( "#content" ).val(content);
}
}
}
I've tried a couple permutations of the following line, which I'd like to alert to only replace text that's not already hyperlinked.
var regex = "/" + target_text + "/";
content = content.replace(regex,replacement_text);
Example attempt:
var regex = "/^(<a.*?>)" + target_text + "^(<\/a>)/";
Can someone please correct me with a regex showing how I should be doing this? No need to explain what the regex does step by step, as I can infer that from the design. Thank you!