DEV Community

Cover image for Using WordPress API with React - Parsing Special Characters
Arifa
Arifa

Posted on

Using WordPress API with React - Parsing Special Characters

While I was working with the WordPress REST API, I encountered that the response from the WordPress API contained few undesired things such as HTML tags and special characters such as ’. For example:

<p>Hey there! A young and eager to learn native English speaker
here. I&#8217;m a Materials Science graduate from the University
of Cambridge and have a broad range of experiences in
engineering and education, from saving elephants in 
South Africa to manufacturing design in Cyprus. I&#8217;m happy
to code and develop my skills as an intern.</p>
Enter fullscreen mode Exit fullscreen mode

I wanted to get rid of the <p> tags and replace the special characters with appropriate human-readable characters.

After spending some time on solving this problem, I found a couple of node packages which solve my problem. They are

  • striptags
  • he

Let's first start with striptags. Install it using:

npm i striptags

Here's an example usage of striptags:

import striptags from 'striptags';
var html = <p>Functional consultant specialized on financials
 modules of Oracle E-Business Suite.</p>

striptags(html);
Enter fullscreen mode Exit fullscreen mode

You can actually do a lot of things with this package, for example, you can decide which tags you want to keep, and which tags you want to replace.

So the next problem was that I was receiving some special characters like I’m, which was meant to be I'm. To solve this,  I made use of a decoder named as he.

Installed the package using:

npm install he

Then, I used the package

import he from 'he';

he.decode('Hey there! A young and eager to learn native English 
speaker here. I&#8217;m a Materials Science graduate from the
University of Cambridge and have a broad range of experiences 
in engineering and education, from saving elephants in South
Africa to manufacturing design in Cyprus. I&#8217;m happy to code
and develop my skills as an intern.');
Enter fullscreen mode Exit fullscreen mode

And the output was

Hey there! A young and eager to learn native English speaker here.
I'm a Materials Science graduate from the University of Cambridge
and have a broad range of experiences in engineering and education, 
from saving elephants in South Africa to manufacturing design
in Cyprus. I'm happy to code and develop my skills as an intern.
Enter fullscreen mode Exit fullscreen mode

I share my learning experience in form of writing blogs, so I write anything new learned. Don’t hesitate to clap if you considered this a worthwhile read!

Top comments (0)