Javascript trim 函数实现

原创
2012/05/28 12:53
阅读数 74

Javascript trim 函数实现

这里是使用了 replace 函数进行的  trim 函数实现。不能够改变原字符串。只能返回 trim 的结果,当然了可以通过 prototype 来使之支持 trim() 函数

 

<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
	// 当然了还可以写成原型链继承
	String.prototype.trim = function(){
		// alert(arguments.length); 为 0
		if(arguments.length == 0){
			return(this.replace(/\s/g,""));
		}else{
			// you can use replace as the same	
		}
	};
	
	window.onload = function(){
		//alert("onload");
		alert(typeofdocument.getElementById("divTest").innerHTML);
		varchangeStr = document.getElementById("divTest").innerHTML;
		
		varchangedStr = changeStr.replace(/\s/g,"");
		alert(changedStr);	// 进行改变之后的字符串进行了 trim() 处理,但是javascript的 String 是不自带 trim 的
		alert(changeStr);	// 改变之前的字符串无变化
		alert(changeStr.trim());	// 使用原型链后也可以使用 trim 函数了
	};
</script>
</head>

<body>
	<div id = "divTest"> this is a divTest</div>

</body>

</html>

 

 

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部