1

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!

buley
  • 28,032
  • 17
  • 85
  • 106
  • 1
    Parsing HTML with regex will cause pain. See [this question](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags), and use a proper parser, or the DOM. – cdhowie Dec 06 '10 at 21:26
  • 3
    Can you give source example of what you're searching? PS: although RE can be problematic with HTML, it's really only when you have nested tags that it starts to break down so don't get too discourage yet....yet. – Keng Dec 06 '10 at 21:40
  • @cdhowie Heh, great link. Reading now. @Keng: Example might be link the word Google to "http://google.com" where it is not already linked somewhere. – buley Dec 06 '10 at 21:40
  • My parsing is rather minimal (I'll keep aware of the nested tags issue). From http://stackoverflow.com/questions/2393017/regular-expression-to-find-text-not-part-of-a-hyperlink, this appears to work for me: `(google)(?!(?:\s*\w*)*)` – buley Dec 06 '10 at 22:12

1 Answers1

1

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\>
Keng
  • 52,011
  • 32
  • 81
  • 111
  • Example text: `Someting about Google that's linked. Something about Google that's not linked. And the actual Google link.` The regex `|()(google)(<\/a>)|` matches only the last Google, the one that's linked. I'd like to match all instances of Google except that one. – buley Dec 06 '10 at 22:03