Uncaught TypeError when using .replace() on HTML5 data attribute storing numbers retrieved with jQuery $.data()

I am storing database values in HTML5 data attributes via jQuery while first escaping them to be HTML attribute safe, and it works fine with Strings.

However, if I've stored a number that doesn't begin with 0, it always gives, for example when the value is 1000:

Uncaught TypeError: Object 1000 has no method 'replace'

How can this be fixed?

html escaper/unescaper

function escapeHtml(unsafe) {
    return unsafe
        .replace(/&/g, "&")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}
function unescapeHtml(unsafe) {
    return unsafe
        .replace(/&amp;/g, "&")
        .replace(/&lt;/g, "<")
        .replace(/&gt;/g, ">")
        .replace(/&quot;/g, "\"")
        .replace(/&#039;/g, "'");
}

I $.append() the element with a String with this data-sortValue="'+sortValue+'" as the HTML5 data.

I try to read it again in another function with unescapeHtml(String($(this).data('sortvalue'))).

Answers


The problem is you are not handling the case where unsafe could be undefined or unsafe is a number/boolean.

Here we can check whether unsafe exists and replace function is available.

function escapeHtml(unsafe) {
    return unsafe && $.isFunction(unsafe.replace) ? unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;") : unsafe;
}
function unescapeHtml(unsafe) {
    return unsafe && $.isFunction(unsafe.replace) ? unsafe
    .replace(/&amp;/g, "&")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&quot;/g, "\"")
    .replace(/&#039;/g, "'") : unsafe;
}

Demo: Fiddle


Need Your Help

Android Sharepreferences Timelimit

android timeout sharedpreferences

In my android application I am using shared preference to remember some inputs so that whenver application get started user dont need to type the input everytime.. now I need to logout the

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.