5 JS practical function code snippets that can be used directly

韦小宝
Release: 2017-11-21 11:28:19
Original
1411 people have browsed it

一波福利,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 + "..." }
Copy after login

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; }
Copy after login

3、原生JavaScript清除空格

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

4、原生JavaScript替换全部

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

5、原生JavaScript转义html标签

function HtmlEncode(text) { return text.replace(/&/g, '&').replace(/\"/g, '"').replace(//g, '>') }
Copy after login

以上的功能源码都是免费提供给大家的,想获取更多就到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!

Related labels:
source:php.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!