String.prototype.lTrim = function(s) {
s = (s ? s : "\\s"); //没有传入参数的,默认去空格
s = ("(" + s + ")");
var reg_lTrim = new RegExp("^" + s + "*", "g"); //拼正则
return this.replace(reg_lTrim, "");
};
String.prototype.rTrim = function(s) {
s = (s ? s : "\\s");
s = ("(" + s + ")");
var reg_rTrim = new RegExp(s + "*$", "g");
return this.replace(reg_rTrim, "");
};
String.prototype.trim = function(s) {
s = (s ? s : "\\s");
s = ("(" + s + ")");
var reg_trim = new RegExp("(^" + s + "*)|(" + s + "*$)", "g");
return this.replace(reg_trim, "");
};
下面是测试代码
<script src="Scripts/trim.js" type="text/javascript"></script>
<script type="text/javascript">
var str1 = " aaaaa ", str2 = "aaasdfdsfaaaa", str3 = "asasddddasas";
document.write("<p>-----空参数测试,多个空格只能在html里显示一个-------</p>");
document.write(str1 + ".lTrim()=" + "\"" + str1.lTrim() + "\"<br/>");
document.write(str1 + ".rTrim()=" + "\"" + str1.rTrim() + "\"<br/>");
document.write(str1 + ".trim()=" + "\"" + str1.trim() + "\"<br/>");
document.write("<p>-----单字符的测试-------</p>");
document.write(str2 + ".lTrim('a')=" + "\"" + str2.lTrim("a") + "\"<br/>");
document.write(str2 + ".rTrim('a')=" + "\"" + str2.rTrim("a") + "\"<br/>");
document.write(str2 + ".trim('a')=" + "\"" + str2.trim("a") + "\"<br/>");
document.write("<p>-----多字符的测试-------</p>");
document.write(str3 + ".lTrim('as')=" + "\"" + str3.lTrim("as") + "\"<br/>");
document.write(str3 + ".rTrim('as')=" + "\"" + str3.rTrim("as") + "\"<br/>");
document.write(str3 + ".trim('as')=" + "\"" + str3.trim("as") + "\"<br/>");
</script>