Home > Back-end >  How to convert string to normal text in JS (reactjs)
How to convert string to normal text in JS (reactjs)

Time:12-21

I was calling in data from an api and data has special characters. For eg in object returned :

{
  question : "In which year did the British television series "The Bill" end?"
}

If I store this value in a variable it saves as a string and when I call this variable using JSX, itthinks its a string and doesn't recognize special characters.

How can I solve this?

export default function Quiz(props){
const element = "In which year did the British television series "The Bill" end?"
        
    return (
         <main>
             {element}
          </main>
            )
  }

I want to render this on the screen

In which year did the British television series "The Bill" end?

CodePudding user response:

You can use a DOMParser to convert your HTML entities into characters by grabbing the innerText of the parsed body element. As we're only dealing with and rendering text content, and not HTML content, we don't need to worry about dangerously setting our HTML (with something like dangerouslySetInnerHTML) that could potentially lead to attacks such as XSS:

const {useMemo} = React;

const App = () => {
  const element = useMemo(() => {
    const str = "In which year did the British television series &quot;The Bill&quot; end?";
    return new DOMParser().parseFromString(str, "text/html").body.innerText;
  }, []);
  return <p>{element}</p>;
};

ReactDOM.createRoot(document.body).render(<App />);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>

CodePudding user response:

You can use the javascript string method replaceAll().

You can use it as string.replaceAll("&quot;","\"")

string = "In which year did the British television series &quot;The Bill&quot; end?";
console.log(string.replaceAll("&quot;","\""));

Run the snippet and you will get the answer you want.

CodePudding user response:

You could create and call a small "sanitise" function that takes a dictionary of key/value pairs, and runs replaceAll on each to swap out the HTML entities.

const data ={
  question: 'In which &lt;year&gt; did the British television series &quot;The Bill&quot; end?'
}

const dict = {
  '&quot;': '"',
  '&gt;': '>',
  '&lt;': '<'
};

function sanitise(str) {
  for (const key in dict) {
    str = str.replaceAll(key, dict[key]);
  }
  return str;
}

console.log(sanitise(data.question));

CodePudding user response:

Here is very simple and easy to use solution without any headache

simply install a react package called react-render-markup and then import in your component where you want to convert this string to plan text it's actually a HTML markup

  • Related