Question

Example text that I am dealing with. This text is a tooltip that is stored in a database that a user can edit using a WYSIWYG editor.

Example tooltip:

BlahBlahBlahBlahBlahBlahBlahBlahBlahBlahBlahBlah
BlahBlahBlahBlah <a href="[SOME_COMPLETE URL]">BlahBlah</a>
BlahBlahBlahBlahBlahBlahBlahBlah

In short I need to replace that href to a javascript function in my app:

<a href="www.myurl.com/page/page/page">BlahBlah</a>

goes to:

<a href="javascript:void(0);" onclick="openOrFocus('www.myurl.com/page/page/page', 'windowName')">BlahBlah</a>

I'm trying to write a RegEx expression to find the href tag, get everything between the quotes. I then need to replace everything between the quotes using the above code and put the URL in the function call.

Here's what I've tried to far but it does not work (I struggle with Regular Expressions)

myTooltipText.replaceAll(".*href\\s*=\\s*\(.*)\"","href=\"javascript:void(0);\" onclick="openOrFocus('[SOME_COMPLETE_URL]', 'windowName')";

I'm using Java and Groovy.

Edit: The URL's are never the same; they change per tooltip as they go to an in depth context help.

Was it helpful?

Solution

You don't need .* before href and you're trying to escape your left parenthesis on your capturing group it looks like. You also missed escaping a quotation inside your replacement text, and left off your ending parenthesis ) at the end of your replaceAll function.

Try the following, this captures between your quotes and references to capture group $1 in the replacement.

myTooltipText.replaceAll("href\\s*=\\s*\"([^\"]*)\"", "href=\"javascript:void(0);\" onclick=\"openOrFocus('$1', 'windowName')\"");

See Working demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top