Javascript Trim

If you prefer not to modify the string prototype, then you can use the stand-alone functions below.


function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
return stringToTrim.replace(/\s+$/,"");
}

// example of using trim, ltrim, and rtrim
var myString = " hello my name is ";
alert("*"+trim(myString)+"*");
alert("*"+ltrim(myString)+"*");
alert("*"+rtrim(myString)+"*");

Example

Type in the box below and you will see the trimmed output dynamically. You must enter spaces before and after the string to see a difference. All whitespace is removed, including tabs and line feeds.

Type text here:
Trim
Left Trim
Right Trim

Compatibility

The functions above use regular expressions, which are compatible with Javascript 1.2+ or JScript 3.0+. All modern (version 4+) browsers will support this. If you require functions for older versions of Javascript back to version 1.0, try the functions below adapted from the Javascript FAQ 4.16. These strip the following, standard whitespace characters: space, tab, line feed, carriage return, and form feed. The IsWhitespace function checks if a character is whitespace.


function ltrim(str) {
for(var k = 0; k < str.length && isWhitespace(str.charAt(k)); k++);
return str.substring(k, str.length);
}
function rtrim(str) {
for(var j=str.length-1; j>=0 && isWhitespace(str.charAt(j)) ; j--) ;
return str.substring(0,j+1);
}
function trim(str) {
return ltrim(rtrim(str));
}
function isWhitespace(charToCheck) {
var whitespaceChars = " \t\n\r\f";
return (whitespaceChars.indexOf(charToCheck) != -1);
}

转载于:https://www.cnblogs.com/xiongeee/archive/2007/10/24/935646.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值