<script??? language=Javascript>????
//自己动手为string添加Trim?????
function???
String.prototype.Trim()???
{return??? this.replace(/(^\s*)|(\s*$)/g,"");}????
function??? String.prototype.Ltrim()
{return??? this.replace(/(^\s*)/g,??? "");}?????
function??? String.prototype.Rtrim()
{return??? this.replace(/(\s*$)/g,??? "");}????? var??? str??? =??? "????? meizz????????? ";????? alert(str.Trim());????? </script>?
利用Javascript中每个对象(Object)的prototype属性我们可以为Javascript中的内置对象添加我们自己的方法和属性。
以下我们就用这个属性来为String对象添加三个方法:Trim,LTrim,RTrim(作用和VbScript中的同名函数一样)
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, "");
}
怎么样,简单吧,下面看一个使用的实例:
<script language=javascript>
String.prototype.Trim = function()
{
???? return this.replace(/(^\s*)|(\s*$)/g, "");
}
var s = "???? leading and trailing spaces???? ";
window.alert(s + " (" + s.length + ")");
s = s.Trim();
window.alert(s + " (" + s.length + ")");
</script>
<script language=Javascript>
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, "!");}
var str = "????????? abc de ";
alert(str.Trim());
</script>
<script>
// 去左右空格
function Trim() {
return this.replace(/\s+$|^\s+/g,"");
}
// 去左空格
function LTrim() {
return this.replace(/^\s+/,"");
}
// 去右空格
function RTrim() {
return this.replace(/\s+$/,"");
}
String.prototype.Trim=Trim;
String.prototype.RTrim=RTrim;
String.prototype.LTrim=LTrim;
</script>
Example.
<script>
var form = document.forms[0];
form.elements[0].value.Trim() ;
</script>
详细解决方案
js往空格函数
热度:338 发布时间:2012-10-26 10:30:59.0
Javascript中为String对象添加??? Trim()??? 方法?????
相关解决方案