javascript中的trim()函数实现

How can I trim a string in JavaScript?


下面的 trim()使用两个正则表达式 字符串前面的空格和尾部的空格,
空格在正则表达式中描述为  /s
The beginning of the string is matched by ^ (see the first regex) and the end is matched by $ - in the second regex.

  1. // implementing a trim function for strings in javascript

  2. <script language="JavaScript" type="text/javascript">
  3. <!--
  4. String.prototype.trim = function () {
  5.     return this.replace(/^/s*/, "").replace(//s*$/, "");
  6. }

  7. var s = new String(" Hello ");
  8. // use it like this
  9. s=s.trim();
  10. alert("!" + s + "!");

  11. // end hiding contents -->
  12. </script>





你可能感兴趣的:(JavaScript,function,正则表达式,String,regex)