js小工具

1.删除字符串空格

/**
* 删除左右两端的空格
*/
String.prototype.trim=function()
{
	 mes = mes.replace( /^\s+|\s+$/g, "" );
     return this.replace(/(^\s*)(\s*$)/g,'');
}
/**
* 删除左边的空格
*/
String.prototype.ltrim=function()
{
     return this.replace(/(^\s*)/g,'');
}
/**
* 删除右边的空格
*/
String.prototype.rtrim=function()
{
     return this.replace(/(\s*$)/g,'');
}
/**
*  删除中间的空格
*  var str="asdf  fff";
*  alert(str.replace("  ","");
*/

 2.使用变量作为属性

var abc = 'abc';
var obj = {
  abc: 'abc-shanshanbox',
  def: 'def-shanshanbox'
}
alert(obj[abc]);

 3.命名空间

$.namespace=function(){
	var a=arguments,b,o=null;
	for(var i=0;i<a.length;i++){
		b=a[i].split('.');
		o=window;
		for(var j=0;j<b.length;j++){
			o[b[j]] = o[b[j]]||{};
			o = o[b[j]];
		}
	}
	return o;
}
$.namespace("hello.namespace");
hello.namespace.alert=function(){
	alert("hahaha");
}

usage:
<button onclick="hello.namespace.alert()">hahah</button>

 4.百度的js模板引擎

5.特殊字符串转换

function encodeHtml(htmlStr) {
	return htmlStr == undefined ? '' :  htmlStr.replace(/&/g,"&amp;")
			.replace(/</g,"&lt;").replace(/>/g,"&gt;")
			.replace(/"/g,"&quot;").replace(/'/g,"&#39;");
}

猜你喜欢

转载自shuizhongyue.iteye.com/blog/2301592