Can I use a regex and foo.replace() to substitute occurances of a string that aren't in anchor tag?
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.
开发者_如何学JAVAvar 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!
I think you want this but I'm not sure that I compeletly understand.
If you use RE to find the text you can assign it to group $1 by putting ()
around it (in this case "Google").
Then when you go to replace it you build the expression with that group assignment id $1
\<a href="$1\.com"\>$1\<\/a\>
精彩评论