日期:2014-05-16  浏览次数:20537 次

一个非常高效的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" onclick="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" onclick="tip()" value="submit">
	</body>
</html>