You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何去除AJAX响应中的ASCII转义字符?API格式处理求助

Fixing HTML Entity Escape Characters from the Quotes on Design API

Hey Stanislaw, I’ve dealt with this exact problem when working with APIs that return HTML-encoded strings—those ’ values are HTML entities (in this case, they represent the right single quote character). Here’s a straightforward, reliable way to convert them to regular text:

The Best Approach: Use the Browser’s Built-in DOMParser

Instead of trying to write regex for every possible HTML entity (which gets messy fast), leverage the browser’s native ability to parse HTML. This method handles all standard entities automatically, so you don’t have to worry about missing edge cases.

Modified Code Example

Here’s how to update your existing code to include entity decoding, building on the logic from your code sample:

// Fetch quote from the API
fetch('https://quotesondesign.com/api-v4-0/')
  .then(response => response.json())
  .then(data => {
    let rawQuote = data.quote;
    
    // Step 1: Remove <p> tags (your existing regex step)
    rawQuote = rawQuote.replace(/<\/?p>/g, '');
    
    // Step 2: Decode HTML entities
    const parser = new DOMParser();
    const decodedQuote = parser.parseFromString(`<div>${rawQuote}</div>`, 'text/html').querySelector('div').textContent;
    
    // Now use the cleaned, decoded quote
    console.log(decodedQuote); // Output: "Communication that doesn’t take a chance doesn’t stand a chance"
  })
  .catch(error => console.error('Error fetching quote:', error));

Why This Works

  • The DOMParser creates a temporary, invisible HTML document with your string wrapped in a <div>.
  • When the browser parses this temporary document, it automatically converts all HTML entities to their corresponding plain-text characters.
  • We extract the text content of the div, giving us clean, unencoded text ready for display.

Alternative: Using a Temporary DOM Element

If you prefer a more concise approach (functionally identical to the DOMParser method), you can use a hidden element to handle decoding:

function decodeHtmlEntities(str) {
  const tempElement = document.createElement('div');
  tempElement.innerHTML = str;
  return tempElement.textContent;
}

// Usage in your code:
rawQuote = decodeHtmlEntities(rawQuote);

This works the same way—letting the browser do the heavy lifting of entity decoding, which is far more robust than trying to manually replace every possible entity with regex.

内容的提问来源于stack exchange,提问作者Stanislaw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:21:36