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, '>')
}
6、原生JavaScript还原html标签
代码如下:
function HtmlDecode(text) {
return text.replace(/&/g, '&').replace(/"/g, '/"').replace(/</g, '<').replace(/>/g, '>')
}
7、原生JavaScript时间日期格式转换
代码如下:
Date.prototype.Format = function(formatStr) {
var str = formatStr;
var Week = ['日', '一', '二', '三', '四', '五', '六'];
str = str.replace(/yyyy|YYYY/, this.getFullYear());
str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));
新闻热点
疑难解答
图片精选