1.字符串长度截取
function cutstr(str, len) { var temp, icount = 0, patrn = /[^\x00-\xff]/, 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.替换全部
String.prototype.replaceAll = function(s1, s2) { return this.replace(new RegExp(s1, "gm"), s2) }
3.清除空格
String.prototype.trim = function() { var reExtraSpace = /^\s*(.*?)\s+$/; return this.replace(reExtraSpace, "$1") }
4.清除左空格/右空格
function ltrim(s){ return s.replace( /^(\s*| *)/, ""); } function rtrim(s){ return s.replace( /(\s*| *)$/, ""); }
5.判断是否以某个字符串开头
String.prototype.startWith = function (s) { return this.indexOf(s) == 0 }
6.判断是否以某个字符串结束
String.prototype.endWith = function (s) { var d = this.length - s.length; return (d >= 0 && this.lastIndexOf(s) == d) }
7.转义html标签
function HtmlEncode(text) { return text.replace(/&/g, '&').replace(/\"/g, '"').replace(//g, '>') }
8.时间日期格式转换
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)); str = str.replace(/MM/, (this.getMonth() + 1) > 9 ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1)); str = str.replace(/M/g, (this.getMonth() + 1)); str = str.replace(/w|W/g, Week[this.getDay()]); str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this