How can I trim a string in JavaScript?
<script type="text/javascript">
</script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
下面的 trim()使用两个正则表达式 字符串前面的空格和尾部的空格,
空格在正则表达式中描述为 /s
The beginning of the string is matched by ^ (see the first regex) and the end is matched by $ - in the second regex.
<script type="text/javascript"> </script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script>
- // implementing a trim function for strings in javascript
- <script language="JavaScript" type="text/javascript">
- <!--
- String.prototype.trim = function () {
- return this.replace(/^/s*/, "").replace(//s*$/, "");
- }
- var s = new String(" Hello ");
- // use it like this
- s=s.trim();
- alert("!" + s + "!");
- // end hiding contents -->
- </script>