直接可用的JS效果

来源:互联网 发布:止水螺栓算法 编辑:程序博客网 时间:2024/06/16 08:38
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, '&amp').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
   }


6、原生JavaScript还原html标签
function HtmlDecode(text) {
         return text.replace(/&amp;/g, '&').replace(/&quot;/g, '\"').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
0 0
原创粉丝点击