0

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)";
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Neli
  • 532
  • 1
  • 3
  • 15

3 Answers3

0
function replaceHTMLEntities(str) {
  const htmlEntities = {
    '&': '&',
    '&lt;': '<',
    '&gt;': '>',
    '&quot;': '"',
    '&#039;': "'",
    '&ndash;': '-',
  };

  return str.replace(/&[\w#]+;/g, entity => {
    return htmlEntities[entity] || entity;
  });
}
MarkBeras
  • 459
  • 1
  • 3
  • 13
0

You can use the method replace() like so:

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

MDN Web Docs - String.prototype.replace()

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
-2

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;'));
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • 1
    This question is an obvious duplicate. Add the answer to that duplicate question if it answers it better than the existing answers. – Heretic Monkey Aug 02 '23 at 14:56