Replace all td tags with th in java line
I want to replace all "td" with "th" in this line
String head = "<tr>\n<td> </td>\n<td> </td>\n<td>Libelle</td>\n"
+ "<td>Nom Table</td>\n<td>Groupe</td>\n<td> </td>\n</tr>\n"
I tried using:
head.replace("<td>", "<th>");
head.replace("</td>", "</th>");
but it doesn't work.
Can you help me?
source to share
In this case, you can use the replace
and method replaceAll
since you are not using any regex and you cannot have nested changes (something like "aaa".replace("a","b")
).
Also, the modified String is returned by the method (and not by implicit modification), so you must reassign the value head
.
So the solution should look like this:
String head = "<tr>\n<td> </td>\n<td> </td>\n<td>Libelle</td>\n<td>Nom Table</td>\n<td>Groupe</td>\n<td> </td>\n</tr>\n";
head = head.replaceAll("<td>", "<th>");
head = head.replaceAll("</td>", "</th>");
System.out.println(head);
EDIT1:
If you only want to change these tags (and always the same ones), you can use replace method
. Otherwise, you should use the method replaceAll
, as it can contain regex expressions. You can find more details on the difference between replace
and replaceAll
at Difference between String replace () and replaceAll ()
source to share