String对象扩展函数概览
以下是对String对象进行的常见功能扩展,旨在增强原生字符串处理能力。
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
return this.replace(/^\s+/g,"");
}
String.prototype.rtrim = function() {
return this.replace(/\s+$/g,"");
}
String.prototype.splitAndTrim = function($delimiter, $limit)
{
var $ss = this.split($delimiter, $limit);
for(var $i=0; $i<$ss.length; $i++)
$ss[$i] = $ss[$i].trim();
return $ss;
}
String.prototype.htmlEntities = function () {
return this.replace(/&/g,'&').replace(//g,'>');
}
String.prototype.stripTags = function () {
return this.replace(/<([^>]+)>/g,'');
}
String.prototype.toArray = function() {
return this.split('');
}
String.prototype.toIntArray = function() {
var returnArray = [];
for (var i=0; i
实现类似其他语言中的占位符替换功能,支持在字符串中通过索引插入变量值。
var a = "I Love {0}, and You Love {1},Where are {0}!";a.format("You","Me");
String.prototype.format = function(){
var args = arguments;
return this.replace(/\{(\d+)\}/g,function(m,i,o,n){
return args[i];
});
}
在现有字符串的末尾追加指定的新字符串内容。
String.prototype.append = function($str){
return this.concat($str);
}
移除指定索引位置的单个字符。若提供的索引超出有效范围,则不执行任何删除操作。
String.prototype.deleteCharAt = function($sIndex){
if($sIndex<0 || $sIndex>=this.length){
return this.valueOf();
}else if($sIndex==0){
return this.substring(1,this.length);
}else if($sIndex==this.length-1){
return this.substring(0,this.length-1);
}else{
return this.substring(0,$sIndex)+this.substring($sIndex+1);
}
}
删除指定起始索引与结束索引之间的子串。注意,$sIndex和$eIndex指向的字符本身不会被删除,该功能依赖于deleteCharAt方法的逻辑。
String.prototype.deleteString = function($sIndex, $eIndex){
if($sIndex==$eIndex){
return this.deleteCharAt($sIndex);
}else{
if($sIndex>$eIndex){
var tIndex=$eIndex;
$eIndex=$sIndex;
$sIndex=tIndex;
}
if($sIndex<0)$sIndex=0;
if($eIndex>this.length-1)$eIndex=this.length-1;
return this.substring(0,$sIndex+1)+this.substring($eIndex,this.length);
}
}
判断当前字符串是否以指定的目标字符串(str)作为结尾。
String.prototype.endsWith = function($str){
return this.substr(this.length - $str.length) == $str;
}
判断当前字符串是否以指定的目标字符串作为开头。
String.prototype.startsWith = function(str){
return this.substr(0, str.length) == str;
}
进行两个字符串的内容比对,忽略字母的大小写差异。
String.prototype.equalsIgnoreCase = function($str){
if(this.length!=$str.length){
return false;
}else{
var tmp1=this.toLowerCase();
var tmp2=$str.toLowerCase();
return tmp1==tmp2;
}
}
将指定的字符串插入到目标位置之后。如果提供的索引无效,则直接将新字符串追加到原字符串末尾。
String.prototype.insert = function($ofset, $str){
if($ofset<0 || $ofset>=this.length-1){
return this.concat($str);
}
return this.substring(0,$ofset)+$str+this.substring($ofset+1);
}
将指定索引位置的字符替换为新的字符或字符串。若索引无效,直接返回原字符串,不做任何修改。
String.prototype.setCharAt = function($ofset, $str){
if($ofset<0 || $ofset>=this.length-1){
return this.valueOf();
}
return this.substring(0,$ofset)+$str+this.substring($ofset+1);
}
String.prototype.replaceLen = function(start, len, replaced) {
if(!len)
return this;
if(start >= this.length)
return this;
var returnSeg = '';
var returnSeg2 = '';
var i = 0;
for (; i < this.length; i++){
var c = this.charAt(i);
if(i < start)
returnSeg += c;
if(i >= start + len)
returnSeg2 += c;
}
return returnSeg + replaced + returnSeg2;
}
对基础类进行扩展,主要用于特定场景下的字符替换,例如将“***天***小时”格式化为“天小时”。
String.prototype.replaceChar = function(target, replaced, start) {
if(!target)
return this;
if(!start)
start = 0;
var returnVal = this.substring(0, start);
var index = 0;
for (var i = start; i < this.length; i++) {
var c = this.charAt(i);
target = typeof target == 'function' ? target.call(this, index) : target;
if (c == target) {
returnVal += typeof replaced == 'function' ? replaced.call(this, index) : replaced;
while (i < this.length - 1 && this.charAt(i + 1) == c) {
i++;
}
index++;
}else{
returnVal += c;
}
}
return returnVal;
}
将当前字符串的顺序完全反转。
String.prototype.reverse = function(){
var str="";
for(var i=this.length-1;i>=0;i--){
str=str.concat(this.charAt(i));
}
return str;
}
计算字符串长度,采用特殊规则:每个汉字计为2个长度单位,每个英文字符计为1个长度单位。
String.prototype.ucLength = function(){
var len = 0;
for(var i=0;i255)len+=2;
else len++;
}
return len;
}
在字符串左侧填充特定的字符,以达到固定长度或对齐效果。
String.prototype.lpad = function(len, s) {
var a = new Array(this);
var n = (len - this.length);
for ( var i = 0; i < n; i++) {
a.unshift(s);
}
return a.join("");
}
在字符串右侧填充特定的字符,以达到固定长度或对齐效果。
String.prototype.rpad = function(len, s) {
var a = new Array(this);
var n = (len - this.length);
for ( var i = 0; i < n; i++) {
a.push(s);
}
return a.join("");
}
将字符串的首字母转换为大写形式,其余部分保持不变。
String.prototype.ucwords = function() {
return this.substring(0,1).toUpperCase().concat(this.substring(1));
}
String.prototype.contains = function($str) {
return this.indexOf($str) > -1 ? true : false;
}
将格式严格为“2008-04-02 10:08:44”的字符串解析并转换为Date日期对象。
String.prototype.toDate = function(){
var str = this.replace(/-/g,"/");
return (new Date(str));
}
将表示十进制数的字符串转换为浮点数,可通过precision参数指定精度。
String.prototype.toFloat = function(precision){
precision = precision || 2;
return parseFloat(this,10).toFixed(precision);
}
将表示十进制数的字符串转换为整数类型。
String.prototype.toInt = function(){
return parseInt(this,10).toString();
}
将两个表示十进制数的字符串相加,并将结果以字符串形式返回,addend参数代表加数。
String.prototype.add = function(addend){
var sum = parseFloat(this,10) + parseFloat(addend,10);
return sum+"";
}
实现十进制数向其他进制的转换,nextScale参数指定目标进制,如2、8、16等。
String.prototype.shiftScale = function(nextScale){
return parseFloat(this).toString(nextScale);
}
实现任意进制之间的互相转换。调用此方法的this对象必须为整数。preScale参数表示原进制,nextScale参数表示目标进制。
String.prototype.scaleShift = function(preScale,nextScale){
return parseInt(this,preScale).toString(nextScale);
}
全角字符转半角字符。示例:document.write("ABC 123,我们都是好朋友"); String.prototype.dbc2sbc = function (){ return this.replace(/[\uff01-\uff5e]/g,function(a){return String.fromCharCode(a.charCodeAt(0)-65248);}).replace(/\u3000/g," "); }
以下是对Array对象进行的常见功能扩展,用于简化数组操作。
var isNumeric = function(x) {
// returns true if x is numeric and false if it is not.
var RegExp = /^(-)?(\d*)(\.?)(\d*)$/;
return String(x).match(RegExp);
}
var myArray = [1,'two',3,'four',5,'six',7,'eight',9,'ten'];
var oddArray=myArray.filter(isNumeric); // outputs: 1,3,5,7,9
var oddArray=myArray.some(isNumeric); // outputs: true
var oddArray=myArray.every(isNumeric); // outputs: false
var printArray =function(x, idx){
document.writeln('['+idx+'] = '+x);
}
myArray.forEach(printArray);// outputs: [0] = 1 [1] = two [2] = 3 [3] = four [4] = 5
myArray.remove(9);
document.writeln(myArray);
if (!Array.prototype.every)
{
Array.prototype.every = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
!fun.call(thisp, this[i], i, this))
return false;
}
return true;
};
}
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
{
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
fun.call(thisp, this[i], i, this);
}
};
}
if (!Array.prototype.map)
{
Array.prototype.map = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
if (!Array.prototype.some)
{
Array.prototype.some = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
fun.call(thisp, this[i], i, this))
return true;
}
return false;
};
}
Array.prototype.sortNum = function() {
return this.sort( function (a,b) { return a-b; } );
}
Array.prototype.find = function(searchStr) {
var returnArray = false;
for (i=0; i
随机打乱数组元素的排列顺序。
Array.prototype.shuffle = function (){
for(var rnd, tmp, i=this.length; i; rnd=parseInt(Math.random()*i), tmp=this[--i], this[i]=this[rnd], this[rnd]=tmp);
return this;
}
Array.prototype.compare = function(testArr) {
if (this.length != testArr.length) return false;
for (var i = 0; i < testArr.length; i++) {
if (this[i].compare) {
if (!this[i].compare(testArr[i])) return false;
}
if (this[i] !== testArr[i]) return false;
}
return true;
}
去除数组中重复的元素。示例:var a = new Array("5","7","7"); a.unique();
Array.prototype.unique = function() {
var data = this || [];
var a = {}; //声明一个对象,javascript的对象可以当哈希表用
for (var i = 0; i < data.length; i++) {
a[data[i]] = true; //设置标记,把数组的值当下标,这样就可以去掉重复的值
}
data.length = 0;
for (var i in a) { //遍历对象,把已标记的还原成数组
this[data.length] = i;
}
return data;
}
Array.prototype.addAll = function($array)
{
if($array == null || $array.length == 0)
return;
for(var $i=0; $i<$array.length; $i++)
this.push($array[$i]);
}
Array.prototype.contains = function($value)
{
for(var $i=0; $i= len)
from = len - 1;
}
for (; from > -1; from--)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
Array.prototype.insertAt = function($value, $index)
{
if($index < 0)
this.unshift($value);
else if($index >= this.length)
this.push($value);
else
this.splice($index, 0, $value);
}
根据指定的数组下标删除对应的元素。
Array.prototype.removeByIndex=function($n) {
if($n<0){ //如果n<0,则不进行任何操作。
return this;
}else{
return this.slice(0,$n).concat(this.slice($n+1,this.length));
}
}
上述删除操作依赖indexOf方法来定位元素索引。
Array.prototype.remove = function($value)
{
var $index = this.indexOf($value);
if($index != -1)
this.splice($index, 1);
}
Array.prototype.removeAll = function()
{
while(this.length > 0)
this.pop();
}
Array.prototype.replace = function($oldValue, $newValue)
{
for(var $i=0; $ilen?len:start?start:0;
delLen=delLen<0?0:delLen>len?len:delLen?delLen:len;
var arr =[],res=[];
var iarr=0,ires=0,i=0;
for(i=0;i=delLen) arr[iarr++]=this[i];
else {
res[ires++]=this[i];
if(item&&ires==delLen){
arr[iarr++]=item;
}
}
}
if(item&&ires
分开添加,关键字shallow copy,如果遇到数组,复制数组中的元素
Array.prototype.concat = function(){
var i=0;
while(ilen?len:end?end:len;
var i=start;
var res = [];
while(i