0

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..

Darshan
  • 4,020
  • 2
  • 18
  • 49

4 Answers4

1

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);
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

try this,
text = text.replaceAll("<br>","").replaceAll("<br>","");

Darshan
  • 4,020
  • 2
  • 18
  • 49
Priyanka
  • 3,369
  • 1
  • 10
  • 33
0

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);
}
0

In these cases, you should take a look at the official Javadoc documentacion:

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)

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.

George
  • 58
  • 7
  • `replace` replaces all – Antoniossss Apr 15 '19 at 06:31
  • 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