jQuery Data Type How to - Add format method to String and Number objects








Question

We would like to know how to add format method to String and Number objects.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--  ww w . ja  v  a2s  .c  om-->
String.prototype.withPct = function () {
    return this + '%';
};
Number.prototype.withPct = function () {
    return this + '%';
};
var str = '10';
var num = new Number(str)
document.body.innerHTML = str.withPct() +'<br /><br />';
document.body.innerHTML += num.withPct();

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: