-1

I am trying to write a custom String.Prototype function:

String.prototype.Apos = function () {
        var string = this.innerHTML.toString();
        return string.replace(/’/g,"'").replace(/“|â€/g,'"');
    }; 

I really just want to write a utf8 string to the browser using javascript, however using decodeURIComponent wont work and so I have just resorted to replacing the apostrophes myself.

So from the examples I've seen I wrote the above function, however it doesnt seem to return anything. When I run the following:

$("span").html(string.Apos);

I don't get a response. I've never written a custom prototype function before so could someone help me out and tell me where Im going wrong?

Chud37
  • 4,278
  • 12
  • 50
  • 98

1 Answers1

1

Do you really need to mess with string.prototype?

You can write a function to do the specific job you want to perform, i.e., replace text.

function replaceQuotes(i, oldHtml) {
    return oldHtml.toString().replace(/’/g,"'").replace(/“|â€/g,'"');
}

And then:

$("span").html(replaceQuotes);
Adeel Zafar Soomro
  • 1,402
  • 9
  • 15
  • No i don't, but it seems to be commonly used and i wanted to learn how it works. My attempt seemed to call and i didn't know why. – Chud37 May 26 '16 at 03:57
  • You'd want to attach functions to string.prototype if you want all string objects to have access to the function as a method. Your use case is so specific that I doubt it makes sense for all string objects to have this method. – Adeel Zafar Soomro May 26 '16 at 05:39