Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ampersand Symbol (&) turning into &

I use the following code to automatically grab/set the latest page title every 30 seconds:

<script type="text/javascript">
   setInterval(function() {
      var data = "http://mysite.com/mypage.php";
      $.get(document.location.toString()).then(function (data){
      //find and set the title of the page
      document.title = data.match(/<title>(.+)<\/title>/)[1];
        });
    }, 30000);
</script>  

It works great, except for titles which include an ampersand. These load normally, and then after 30 seconds are replaced with:

&amp;

So if the page title is:

Fun & Games

After 30 seconds, it becomes:

Fun &amp; Games

Thanks

like image 368
PF Billing Avatar asked Oct 21 '25 10:10

PF Billing


2 Answers

Instead of using a regex to extract the title, try asking the DOM what the title of the returned page is. The problem is, in your file, it's &amp;, but once it's parsed it becomes &.

$.get(document.location.toString()).then(function (data){
    //find and set the title of the page
    document.title = $(data).filter('title').text();
});
like image 185
Rocket Hazmat Avatar answered Oct 23 '25 00:10

Rocket Hazmat


I'm assuming your raw HTML source has something like <title>Fun &amp; Games</title>, which is what it should have to be valid.

This is fine when it's processed by the browser, as it will understand the &amp; as an ampersand.

However, in the context of JavaScript, setting document.title is a plain string, not one parsed by HTML. Therefore, the &amp; is not interpreted, and is left as is.

Personally, I have a function called unHTMLref in my "toolbox", defined as so:

window.unHTMLref = function(str) {
    if( !str) return str;
    var d = document.getElementById('__unHTMLref');
    if( !d) {
        d = document.createElement('div');
        d.id = '__unHTMLref';
        d.style.display = "none";
        document.body.appendChild(d);
    }
    d.innerHTML = str.replace(/</g,'&lt;');
    return d.firstChild.nodeValue;
};

This will decode all HTML entities, and return the parsed string.

like image 26
Niet the Dark Absol Avatar answered Oct 23 '25 02:10

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!