skip to Main Content

I have a string with multiple different HTML characters in it.
For example:

var price = "CHF 150.– (brutto)";

how can I replace the HTML entities like – with the string character like below?

"CHF 150.- (brutto)";

3

Answers


  1. function replaceHTMLEntities(str) {
      const htmlEntities = {
        '&': '&',
        '&lt;': '<',
        '&gt;': '>',
        '&quot;': '"',
        '&#039;': "'",
        '&ndash;': '-',
      };
    
      return str.replace(/&[w#]+;/g, entity => {
        return htmlEntities[entity] || entity;
      });
    }
    
    Login or Signup to reply.
  2. You can use the method replace() like so:

    price.replace('&ndash', '-');
    

    MDN Web Docs – String.prototype.replace()

    Login or Signup to reply.
  3. You could decode it using the native DOMParser.

    I created a wrapper class that can be reused:

    // Based on: https://stackoverflow.com/a/34064434/1762224
    class HTMLDecoder {
      constructor() {
        this.parser = new DOMParser();
      }
      decode(input) {
        const doc = this.parser.parseFromString(input, 'text/html');
        return doc.documentElement.textContent;
      }
    }
    
    const decoder = new HTMLDecoder(),
          price   = "CHF 150.&ndash; (brutto)";
    
    console.log(decoder.decode(price));
    
    console.log(decoder.decode('&copy; 2023 &quot;Hello World&quot;'));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search