Last active
August 29, 2015 13:57
-
-
Save mindon/9499857 to your computer and use it in GitHub Desktop.
String simple size / limit / html / text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// usage | |
// var s = "This is a 非常长的字符串This is a 非常长的字符串This is a 非常长的字符串This is a 非常长的字符串"; | |
// document.write(s.limit(20)); | |
// character length | |
String.prototype.size = function() { | |
var s = this, n = 0; // [u4e00-u9fa5] chinese | |
if(s) n = s.replace(/[^\x00-\xff]/g, "**").length; | |
return n; | |
}; | |
// limit trim postfix with ... | |
String.prototype.limit = function(n, ishtml) { | |
var s = (ishtml&&this.length>0?this.html():this); | |
if(s && s.size() > n) { | |
var l = s.length, u = s.substr(0, n>l?l-3:n-3); | |
if(u.size() < n-3) u = s.substr(0, n-2); | |
return "<span title=\""+this.replace(/\"/g,'"')+"\">" +(ishtml?u.text():u) +"..." +"</span>"; | |
} else { | |
return ishtml?s.text():s; | |
} | |
}; | |
var parser = document.createElement('div'); | |
// unescape html text (& => &) | |
String.prototype.html = function() { | |
if(this.length==0) return this; | |
var o = parser; o.innerHTML = this; | |
return (o.innerText === undefined? o.textContent: o.innerText); | |
}; | |
String.prototype.text = function() { | |
if(this.length==0) return this; | |
var o = parser; if(o.innerText === undefined) o.textContent = this; else o.innerText = this; | |
return o.innerHTML; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment