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?
String.replace(..)
will return the resulting string, so you need to set it back
head = head.replace("<td>", "<th>");
head = head.replace("</td>", "</th>");
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 ()
You can have one line.
head = head.replaceAll("td>", "th>");
This is when it comes to scripts like empty tags <td /><td/>
and when tags td
have attributes like class=\"abc\"
:
String head = ""<td class=\"abc\">outdoor</td><td />"";
head = head.replace("<td", "<th");
head = head.replace("</td", "</th");
System.out.println(head);
replace methods return a new string.
String s = "hi hi hi";
Line f = s.replace ("hi", "bye");
System.out.println (s + "----" + f);
prints: hello hello goodbye bye bye