1

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>  

4 Answers4

2

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.
Burak Yücel
  • 313
  • 3
  • 11
1

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']}

Rakesh Medpalli
  • 416
  • 3
  • 11
  • 1
    i don't want to remove whole p tags but i have to remove only empty p tags and p tag containing  

    some text

    ----- i don't want to remove this

    ----- i want to remove this empty p tag

     

    ----- i also want to remove this p tag
    – Binit Chandra Jha Aug 07 '20 at 05:16
0

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, '');
Ali Hasan
  • 3,843
  • 1
  • 5
  • 9
0

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}
 />
Siddhartha Mukherjee
  • 2,703
  • 2
  • 24
  • 29