Suppose I have a String
with multiple <br>
tags at the end of the String,
how can I remove all at once?
I've tried using if(text.endsWith("<br>") text.replace("<br>", "");
but that only removes one of all the others..
4 Answers
If you only want to remove them at the end of the string:
text = text.replaceAll("(<br>)*$", "");
The $
anchor is necessary to ensure that this doesn't replace other occurrences earlier in the string.
You can do it without regex, if you want:
int a = text.length();
while (a >= "<br>".length() && text.regionMatches(a - "<br>".length(), "<br>", 0, "<br>".length())) {
a -= "<br>".length();
}
text = text.substring(0, a);

- 137,514
- 11
- 162
- 243
I don't think that there is a specific method in java to do this. However, you can use a while loop to achieve this :
String text = "hello world <br><br><br>";
while (text.endsWith("<br>")) {
text = text.substring(0, text.length() - 4);
}

- 189
- 1
- 11
In these cases, you should take a look at the official Javadoc documentacion:
The method you're looking for is public String replaceAll(String regex, String replacement), which replaces all the occurrences of the specified pattern. In your case it should be something like this:
fullText.replaceAll("<br>", ""),
where fullText is the variable that contains all the text you want to process.
EDIT: From your comments I gather you only want to delete the br at the end of the string and I assume that text is compromised of multiple lines. Since replaceAll can use regular expression, you should be able to do something like this:
fullText.replaceAll("<br>\\n", "\\n"),
EDIT 2: I wish I could comment...Disregard my answer, please, I think the correct answer is Andy Turner's one. It does seem to work fine at only deleting the br at the end of the line.

- 58
- 7
-
-
You're right, if you're not using a regular expression to process the string then you can use replace instead of replaceAll. In this case I've updates the answer since it needs a regEx. – George Apr 15 '19 at 06:41
-
1@George newlines don't only occur at the end of strings, nor do they necessarily appear at the end of a string. And in particular, there is no newline at the end of OP's string. – Andy Turner Apr 15 '19 at 06:51
-
You're right, the problem was that I didn't fully understand the question, but I already edited the answer to reflect that I was wrong. Thanks for the input. – George Apr 15 '19 at 07:19
", "");` – Pavel Smirnov Apr 15 '19 at 06:24
` tags in the string, I only want to remove the multiple tags in the end of the String – Darshan Apr 15 '19 at 06:28
', ''); You can see doc..https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace – Jabongg Apr 15 '19 at 06:30