Trim //JavaScript Repository
Description
Clears undesirable characters on the left, right or both sides.
Created: 2005.08.11
Created: 2005.08.11
Code (Download)
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/string/trim [rev. #1]
String.prototype.trim = function(c, t){
return c = "[" + (c == undefined ? " " : c.replace(/([\^\]\\-])/g, "\\\$1")) + "]+",
this.replace(new RegExp((t != 2 ? "^" : "") + c + (t != 1 ? "|" + c + "$" : ""), "g"), "");
};
Example (Example)
<script type="text/javascript">
//<![CDATA[
document.write(
'"', s = ".......Exemplo=======", '".trim(".=") = ', s.trim(".="), "<br />",
'"', s = ".......Exemplo.......", '".trim(".", 1) = ', s.trim(".", 1), "<br />",
'"', s = "Exemplo11111112222222", '".trim("12") = ', s.trim("21")
);
//]]>
</script>
Help
- String.prototype.trim([chars: String = " "], [type: Integer = 0]): String
-
Remove characters on the left, right or both sides of the string.
- chars
- set of characters that will be removed
- type
- specifies where the trim will occur, possible values are:
- 0 = remove on both sides
- 1 = remove characters on the left
- 2 = remove characters on the right
Rank (Votes: 29)
3.59