0

I am trying to replace a pattern as below: Original :

<a href="#idvalue">welocme</a>

Need to be replaced as :

<a href="javascript:call('idvalue')">welcome</a>

Tried the below approach:

String text = "<a href=\"#idvalue\">welocme</a>";
Pattern linkPattern = Pattern.compile("a href=\"#");
text =  linkPattern.matcher(text).replaceAll("a href=\"javascript:call()\"");

But not able to add the idvalue in between. Kindly help me out. Thanks in advance.

2

3 Answers 3

1

how about a simple

text.replaceAll("#idvalue","javascript:call('idvalue')")

for this case only. If you are looking to do something more comprehensive, then as suggested in the other answer, an XML parser would be ideal.

Sign up to request clarification or add additional context in comments.

Comments

1

Try getting the part that might change and you want to keep as a group, e.g. like this:

text = text.replaceAll( "href=\"#(.*?)\"", "href=\"javascript:call('$1')" );

This basically matches and replaces href="whatever" with whatever being caught by capturing group 1 and reinserted in the replacement string by using $1 as a reference to the content of group 1.

Note that applying regex to HTML and Javascript might be tricky (single or double quotes allowed, comments, nested elements etc.) so it might be better to use a html parser instead.

Comments

0

Add a capture group to the matcher regex and then reference the group in the replacemet. I found using the JavaDoc for Matcher, that you need to use '$' instead of '\' to access the capture group in the replacement.

Code:

String text = "<a href=\"#idvalue\">welcome</a>";
System.out.println("input: " + text);       
Pattern linkPattern = Pattern.compile("a href=\"#([^\"]+)\"");
text =  linkPattern.matcher(text).replaceAll("a href=\"javascript:call('$1')\"");
System.out.println("output: " +text);

Result:

input: <a href="#idvalue">welcome</a>
output: <a href="javascript:call('idvalue')">welcome</a>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.