0

I have a string containing HTML and a JSON string... I retrieve this string calling an API. My objective is to retrieve the JSON object from it.

I'm setting 2 variables containing the html beginning and ending and a third empty string.

htmlStart = '<html><body><h1>Response</h1><p>The server returned these fields:<p><table border="1"><tr><td>JSONResponse</td><td>';
htmlEnd = '</td></tr></table></body></html>';
response = '';

I try to use some regex to remove '\n' and replace to change the final string output.

ngOnInit(): void {
  this.apiService.getCategories().subscribe(
    (res) => {
      console.log(typeof res);

      this.response = res
        .replace(/\n/g, '')
        .replace(this.htmlStart, '')
        .replace(this.htmlEnd, '');
      console.log(this.response);
    }
  );

It seems that the replace function is not working.

1 Answer 1

2

Since the response contains well formed HTML, you can simply treat it as such.

const responseElement = document.createElement('html');
responseElement.innerHTML = this.htmlStart;
const jsonString = responseElement.querySelector('td').textContent;
return JSON.parse(jsonString);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.