Binit Chandra Jha
Binit Chandra Jha

Reputation: 89

how to remove empty p tag and &nbsp from html in react-native

i want to remove empty p tag and &nbsp from dynamic html content.

below is html content retrieved from api response. empty p tag and &nbsp creates unwanted whitespace. i want to remove unwanted whitespace.

i am using react-native-render-html package to display the html content.

expo sdk : 38 
react-native-render-html : ~1.9.0 
platform : Android,Ios

<p> </p>
<p> &nbsp </p>  

Upvotes: 2

Views: 5351

Answers (4)

Siddhartha Mukherjee
Siddhartha Mukherjee

Reputation: 2961

I have used it, It worked fantastically

import HTMLView from 'react-native-htmlview';

htmlText = htmlText.replace(/(\r\n|\n|\r)/gm, '');

 <HTMLView
    stylesheet={htmlStyles}
    addLineBreaks={false}
    value={htmlText}
 />

Upvotes: 0

Ali Hasan
Ali Hasan

Reputation: 4353

Use this regular expression to remove html tags (except &nbsp;)

const regEx = /(<([^>]+)>)/ig;
const tempResult = yourData.replace(regEx, '');

If html response contains &nbsp; then follow additional step:

const secondRegEx = /((&nbsp;))*/gmi;
const result = tempResult.replace(secondRegEx, '');

Upvotes: 0

Rakesh Medpalli
Rakesh Medpalli

Reputation: 474

In react-native-render-html there is a option for ignoring tag.

import { IGNORED_TAGS } from 'react-native-render-html/src/HTMLUtils';
...
 
// your props
ignoredTags={[ ...IGNORED_TAGS, 'tag1', 'tag2']}

Upvotes: 1

Burak Y&#252;cel
Burak Y&#252;cel

Reputation: 313

Sanitizing the output in the server would be better but according to your question, you can use a RegExp like this:

/<p>(\s|(&nbsp))*<\/p>/gmi

Example:

var string = "<p>  &nbsp   &nbsp  </p>";
var pattern = /<p>(\s|(&nbsp))*<\/p>/gmi;
var result = str.match(patt);

if(result) {
     console.log("Pattern matched. Do not add the string to the html.")
}

Pattern explanation:

  • The first <p> is the plain p element characters.
  • (\s|(&nbsp))* tells that there would be char groups that contain spaces, or &nbsp character string. If you find those zero time or more, match them.
  • Final <\/p> is the finishing p element. Inverted slash comes before the slash, because normal slash is a special character in RegExp. So we are escaping it with inverted slash.

Upvotes: 2

Related Questions