一波福利,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, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>')
}
以上的功能源码都是免费提供给大家的,想获取更多就到搜索吧!
相关推荐:
js实现电商触摸放大图效果
js循环轮播图
js实现背景动画分裂
以上就是5个直接可以拿来用的js实用功能代码片段的详细内容。