How to remove HTML from a text string in Java

Cloudmersive
2 min readFeb 13, 2020

It’s smart to have HTML script attacks on your radar; they can cause some major headaches. Today we are going to look at how to filter out scripts from a text string, giving you an extra layer of protection against this threat. Not only that, we are going to get this done in a real hurry.

First things first, we need our library. We are going to dynamically compile this with Jitpack, so we need to add some references to pom.xml.

Repository

<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>

Dependency

<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v3.34</version>
</dependency>
</dependencies>

Now call editTextRemoveHtml, as we have demonstrated here:

// Import classes://import com.cloudmersive.client.invoker.ApiClient;//import com.cloudmersive.client.invoker.ApiException;//import com.cloudmersive.client.invoker.Configuration;//import com.cloudmersive.client.invoker.auth.*;//import com.cloudmersive.client.EditTextApi;ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: ApikeyApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");Apikey.setApiKey("YOUR API KEY");// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)//Apikey.setApiKeyPrefix("Token");EditTextApi apiInstance = new EditTextApi();RemoveHtmlFromTextRequest request = new RemoveHtmlFromTextRequest(); // RemoveHtmlFromTextRequest | Input requesttry {RemoveHtmlFromTextResponse result = apiInstance.editTextRemoveHtml(request);System.out.println(result);} catch (ApiException e) {System.err.println("Exception when calling EditTextApi#editTextRemoveHtml");e.printStackTrace();}

And the API does the hard work for us! Any HTML — and the potential hazards they carry — have now been stripped out of our string.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.