-1

I have a simple html string like '<html><body><h1>hello world!!!!!</h1></body></html>'. I want to convert it to text but I am getting error like .text is not a function

My main purpose is to convert url into html. This is my code

      axios({
            method: 'get',
            url: url,
            headers:{
                "Content-Type":"text/html"
            },
        }).then(async (res) => {     
                const html = await res.data.text();
                console.log('html:', html);
        }).catch((e) => {
            console.log('e: ', e);
        })

I consoled res.data and I got html string but I am not able to convert it to text. I tried to put hardcoded html string to .text() but I am getting the same error that .text is not a function

Is there .text() method ? Why am I getting this error ? Does anybody have other solution ?

Srushti Shah
  • 810
  • 3
  • 17
  • 1
    If `res.data` is the string.. then just use that string? You already have the string. What would be the purpose of trying to chain on another `.text()`? (You'd use `.then(res => res.text())` when using fetch, but not here) – CertainPerformance Sep 21 '22 at 04:42
  • I have asked question on https://stackoverflow.com/questions/73787816/how-to-convert-url-into-html-in-javascript/73788052#73788052 can you please refer that to know what exactly I am gonna do – Srushti Shah Sep 21 '22 at 04:44
  • My comment still stands... that uses fetch, not axios – CertainPerformance Sep 21 '22 at 04:45
  • Your GET request has no content and therefore does not require a content-type header. What makes you think a plain [String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#instance_methods) would have a `text()` method? All you need is `const html = res.data;` – Phil Sep 21 '22 at 04:46

2 Answers2

2

If you're looking to get out of it only hello world!!!!!, then use DOMParser to turn it into a document, then get the document's text content.

axios(url)
  .then((res) => {     
    const htmlText = res.data;
    const doc = new DOMParser().parseFromString(htmlText, 'text/html');
    const plainTextContent = doc.body.textContent.trim();
    // use plainTextContent
  }).catch((e) => {
    console.log('e: ', e);
  });
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

If you specify the responseType in your request options, you can directly receive an HTML document without having to worry about parsing it

// just an example HTML page
const url = "https://jsonplaceholder.typicode.com/index.html";

axios.get(url, { responseType: "document" }).then(({ data }) => {
  // data is an HTML document
  const title = data.querySelector("h1").textContent;
  console.log("title:", title);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js" integrity="sha512-odNmoc1XJy5x1TMVMdC7EMs3IVdItLPlCeL5vSUPN2llYKMJ2eByTTAIiiuqLg+GdNr9hF6z81p27DArRFKT7A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

This is possible because Axios (when run in the browser) uses XMLHttpRequest which automatically supports rich (parsed) response types.

The Fetch API which is used in the post you linked to unfortunately does not support such a convenience and the response must be parsed.

Phil
  • 157,677
  • 23
  • 242
  • 245