一个非常高效的js的trim截取字符串-原生方法-正则表达式

第一种非常高效的原生方法:

 

<html>
	<head>
		<script type = "text/javascript">
		// prototype trim method ,a very effective method of to trim a String 
		String.prototype.trim = function() { 
			return this.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); 
		} 
		function tip(){
			var tipMessage = document.getElementById("test").value;
			alert(tipMessage.trim().length);
		}
		</script>
	</head>
	<body>
		<input type="text" name = "test" style="width:100px">
		<input type="button" οnclick="tip()" value="submit">
	</body>
</html>
 

 

第二种方法更高效,直逼二进制,这不是牛人写的,这是神写的!

附上js三元运算:

var test = document.getElementById("test").value;  

var flag =  (test=="a")?"a":( (test=="b")?"b":(test=="c"?"c":"other"));

alert(flag);

 

<html>
	<head>
		<script type = "text/javascript">
		// prototype trim method ,a very effective method of to trim a String 
		String.prototype.trim = function() { 
			var str = this, 
			whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
			for (var i = 0,len = str.length; i < len; i++) { 
				if (whitespace.indexOf(str.charAt(i)) === -1) { 
					str = str.substring(i); 
					break; 
				} 
			} 
			for (i = str.length - 1; i >= 0; i--) { 
				if (whitespace.indexOf(str.charAt(i)) === -1) { 
					str = str.substring(0, i + 1); 
					break; 
				} 
			} 
			return whitespace.indexOf(str.charAt(0)) === -1 ? str : ''; 
		} 
		function tip(){
			var tipMessage = document.getElementById("test").value;
			alert(tipMessage.trim().length);
		}
		</script>
	</head>
	<body>
		<input type="text" name = "test" style="width:100px">
		<input type="button" οnclick="tip()" value="submit">
	</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值