一波福利,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, '>') }
以上的功能源码都是免费提供给大家的,想获取更多就到PHP中文网搜索吧!
相关推荐:
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!