Search code examples
javascriptregexreplacehrefappcelerator

Replace a href with a js function call


I want to replace an url in a href with a call of a function that needs to include the url.

example: I have the following string:

<a href="www.google.com">Google</a>
some other text
<a href="www.wikipedia.org">Wikipedia</a>

I want to get back a string like this:

<a href="javascript:anyFunction('www.google.com');">Google</a>
some other text
<a href="javascript:anyFunction('www.wikipedia.org')">Wikipedia</a>

I have tested some ways with RegEx, but I'm not good with RegEx. Does anyone have a solution for my problem?

EDIT: Sorry, I forgot to write. I'm building an appcelator application. I can't use jQuery or "document". I think the only way is a RegEx.


Solution

  • Give this regex a try:

    /href="([^"]+)/g
    

    Here is a sample of its usage (JsFiddle Demo)

    var subject = '<a href="www.google.com">Google</a>some other text<a href="www.wikipedia.org">Wikipedia</a>';
    var result = subject.replace(/href="([^"]+)/g, 'href="javascript:anyFunction(\'$1\')');