Home Web Front-end JS Tutorial Share some commonly used extensions of js objects

Share some commonly used extensions of js objects

Jul 11, 2018 pm 05:11 PM
js object

这篇文章主要介绍了关于分享一下js对象常用的扩展,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

//js string对象扩展
(function() {
    // 除去两边空白 
    String.prototype.trim = function() {
        return this.replace(/(^\s*)|(\s*$)/g, "");
    };
    //截取字符串了 
    String.prototype.cutStr = function(len) {
        var str = this;
        var str_length = 0;
        var str_len = 0;
        str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4  
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度,则返回源字符串;  
        if (str_length < len) {
            return str;
        }
    };
    // 保留中文 
    String.prototype.getCn = function() {
        return this.replace(/[u4e00-u9fa5uf900-ufa2d]/g, "");
    };
    // 保留数字 
    String.prototype.getNum = function() {
        return this.replace(/[^\d]/g, "");
    };
    // 保留字母 
    String.prototype.getEn = function() {
        return this.replace(/[^A-Za-z]/g, "");
    };
    //从右边截取,到终点字符位置
    String.prototype.subIndexStr = function(str) {
        var index = this.indexOf(str);
        return this.substr(0, index);
    };
    // 从左截取指定长度的字串 
    String.prototype.left = function(n) {
        return this.slice(0, n);
    };
    // 从右截取指定长度的字串 
    String.prototype.right = function(n) {
        return this.slice(this.length - n);
    };
    // HTML编码 
    String.prototype.HTMLEncode = function() {
        var re = this;
        var q1 = [/x26/g, /x3C/g, /x3E/g, /x20/g];
        var q2 = ["&", "<", ">", " "];
        for (var i = 0; i < q1.length; i++)
            re = re.replace(q1[i], q2[i]);
        return re;
    };
    //字符串转换为日期格式
    String.prototype.toDate = function() {
        if (isNaN(this) && !isNaN(Date.parse(this))) {  
            return new Date(this);
        } else {
            console.error(this == null ? "不是日期格式" : this + "不是日期格式")
        }
    };
    //左边补零
    String.prototype.padLeftZero = function(n) {
        return Array(n > this.length ? (n - (&#39;&#39; + this).length + 1) : 0).join(0) + this;
    };
    //右边补零
    String.prototype.padRightZero = function(n) {
        return this + Array(n > this.length ? (n - (&#39;&#39; + this).length + 1) : 0).join(0);
    };
    //转换人民币格式
    String.prototype.toRenminbi = function() {
        var n = this.replace(/,/g, &#39;&#39;);;
        var fraction = [&#39;角&#39;, &#39;分&#39;];
        var digit = [&#39;零&#39;, &#39;壹&#39;, &#39;贰&#39;, &#39;叁&#39;, &#39;肆&#39;, &#39;伍&#39;, &#39;陆&#39;, &#39;柒&#39;, &#39;捌&#39;, &#39;玖&#39;];
        var unit = [
            [&#39;元&#39;, &#39;万&#39;, &#39;亿&#39;],
            [&#39;&#39;, &#39;拾&#39;, &#39;佰&#39;, &#39;仟&#39;]
        ];
        var head = n < 0 ? &#39;欠&#39; : &#39;&#39;;
        n = Math.abs(n);

        var s = &#39;&#39;;

        for (var i = 0; i < fraction.length; i++) {
            s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, &#39;&#39;);
        }
        s = s || &#39;整&#39;;
        n = Math.floor(n);

        for (var i = 0; i < unit[0].length && n > 0; i++) {
            var p = &#39;&#39;;
            for (var j = 0; j < unit[1].length && n > 0; j++) {
                p = digit[n % 10] + unit[1][j] + p;
                n = Math.floor(n / 10);
            }
            s = p.replace(/(零.)*零$/, &#39;&#39;).replace(/^$/, &#39;零&#39;) + unit[0][i] + s;
        }
        return head + s.replace(/(零.)*零元/, &#39;元&#39;).replace(/(零.)+/g, &#39;零&#39;).replace(/^整$/, &#39;零元整&#39;);
    };
    String.prototype.amountFormat = function() {
        var number = this;
        var decimals = 2;
        number = (number + &#39;&#39;).replace(/[^0-9+-Ee.]/g, &#39;&#39;);
        var n = !isFinite(+number) ? 0 : +number,
            prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
            sep = (typeof thousands_sep === &#39;undefined&#39;) ? &#39;,&#39; : thousands_sep,
            dec = (typeof dec_point === &#39;undefined&#39;) ? &#39;.&#39; : dec_point,
            s = &#39;&#39;,
            toFixedFix = function(n, prec) {
                var k = Math.pow(10, prec);
                return &#39;&#39; + Math.floor(n * k) / k;
            };
        s = (prec ? toFixedFix(n, prec) : &#39;&#39; + Math.floor(n)).split(&#39;.&#39;);
        var re = /(-?\d+)(\d{3})/;

        while (re.test(s[0])) {
            s[0] = s[0].replace(re, "$1" + sep + "$2");
        }

        if ((s[1] || &#39;&#39;).length < prec) {
            s[1] = s[1] || &#39;&#39;;
            s[1] += new Array(prec - s[1].length + 1).join(&#39;0&#39;);
        }
        return s.join(dec);
    };
})();

//js  Date 时间对象扩展
(function() {
    Date.prototype.toString = function(fmt) {
        function padLeftZero(str) {
            return (&#39;00&#39; + str).substr(str.length);
        }
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + &#39;&#39;).substr(4 - RegExp.$1.length));
        }
        let o = {
            &#39;M+&#39;: this.getMonth() + 1,
            &#39;d+&#39;: this.getDate(),
            &#39;h+&#39;: this.getHours(),
            &#39;m+&#39;: this.getMinutes(),
            &#39;s+&#39;: this.getSeconds()
        };
        for (let k in o) {
            if (new RegExp(`(${k})`).test(fmt)) {
                let str = o[k] + &#39;&#39;;
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
            }
        }

        return fmt;
    }
})();
Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

 分享Nodejs接入微信JS-SDK的全过程

对于JS模块化的解析

对于Javascript加载的解析

The above is the detailed content of Share some commonly used extensions of js objects. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles