Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String replace not working [duplicate]

String delimiter = "\\*\\*";
String html = "<html><head></head><body>**USERNAME** AND **PASSWORD**</body></html>";
Map<String, String> mp = new HashMap<String, String>();
mp.put("USERNAME", "User A");
mp.put("PASSWORD", "B");
for (Entry<String, String> entry : mp.entrySet()) {
  html.replace(delimiter + entry.getKey()+ delimiter, entry.getValue());
}

That should usually replace those both strings, but it does not. Does anyone has an idea?

like image 775
Vilius Avatar asked Jun 02 '11 19:06

Vilius


1 Answers

String is immutable, which means that the html reference doesn't change, rather the replace method returns a new String object that you have to assign.

html = html.replace(delimiter + entry.getKey()+ delimiter, entry.getValue());
like image 66
Yishai Avatar answered Oct 13 '22 08:10

Yishai