0

In JavaScript, how can I convert a string containing HTML entities to uppercase. Take the string 'Cafés & Bars' for example:

Cafés & Bars

It needs to be converted to:

CAFÉS & BARS

If toUpperCase() were used, it would destroy both the entities. If the text were to be uppercased and then text between & and ; were lowercased then the acute E would remain lowercase.

In my particular case, I am unable to solve this using the text-transform: uppercase style.

Simon Cave
  • 3,971
  • 4
  • 24
  • 28

3 Answers3

1
function decodeEntities(string){
var elem = document.createElement('div');
elem.innerHTML = string;
return elem.textContent;
}

Then simply do something like decodeEntities('Cafés & Bars').toUpperCase(); But note that when you do, your returned text won't be CAFÉS & BARS it will be CAFÉS & BARS

Some Guy
  • 15,854
  • 10
  • 58
  • 67
  • you way is much nicer than my version – david Nov 03 '11 at 06:07
  • @david Thank you. It's good that you're providing for browser incompatibilities by using textContent or innerText, depending on which is available. Note that you don't actually need to append the element or give it an id. Just create it, give it its innerHTML to decode and get its value back from the reference of the created element. – Some Guy Nov 03 '11 at 06:13
0

If you have control of the text representation, you can use (or convert text-named entities to) decimal HTML entities; they don't get converted to uppercase, because numbers have only one case.

So:

Instead of & use &
Instead of < use &#60
Instead of " use "

etc.

fyngyrz
  • 2,458
  • 2
  • 36
  • 43
0

I'm hoping there's enough examples in this fiddle to solve things for you. FYI, you don't mention if you are using jQuery or not, I can update this if you need just vanilla JS.

http://jsfiddle.net/hafichuk/APNWh/

hafichuk
  • 10,351
  • 10
  • 38
  • 53