Home >Web Front-end >JS Tutorial >5 JS practical function code snippets that can be used directly

5 JS practical function code snippets that can be used directly

韦小宝
韦小宝Original
2017-11-21 11:28:191524browse

一波福利,JS功能源码在这,看看有没有你需要的,拿走直接放在JS的项目中用,或者用来学习JS。

不废话,直接上代码

1、原生JavaScript实现字符串长度截取

  function cutstr(str, len) {
         var temp;
         var icount = 0;
         var patrn = /[^\x00-\xff]/;
         var strre = "";
         for (var i = 0; i < str.length; i++) {
             if (icount < len - 1) {
                 temp = str.substr(i, 1);
                 if (patrn.exec(temp) == null) {
                     icount = icount + 1
                } else {
                     icount = icount + 2
                 }
                 strre += temp
             } else {
                break
             }
        }
        return strre + "..."
     }

2、原生JavaScript获取域名主机

function getHost(url) {
         var host = "null";
        if(typeof url == "undefined"|| null == url) {
             url = window.location.href;
         }
         var regex = /^\w+\:\/\/([^\/]*).*/;
         var match = url.match(regex);
         if(typeof match != "undefined" && null != match) {
             host = match[1];
        }
        return host;
}

3、原生JavaScript清除空格

   String.prototype.trim = function() {
       var reExtraSpace = /^\s*(.*?)\s+$/;
       return this.replace(reExtraSpace, "$1")
     }

4、原生JavaScript替换全部

String.prototype.replaceAll = function(s1, s2) {
         return this.replace(new RegExp(s1, "gm"), s2)
   }

5、原生JavaScript转义html标签

function HtmlEncode(text) {
         return text.replace(/&/g, &#39;&amp&#39;).replace(/\"/g, &#39;&quot;&#39;).replace(/</g, &#39;&lt;&#39;).replace(/>/g, &#39;&gt;&#39;)
   }

以上的功能源码都是免费提供给大家的,想获取更多就到PHP中文网搜索吧!

相关推荐:

JS实现电商触摸放大图效果

JS循环轮播图

js实现背景动画分裂

The above is the detailed content of 5 JS practical function code snippets that can be used directly. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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