4-6 字符串操作函数
本节编程练习不计算学习进度,请电脑登录imooc.com操作

字符串操作函数

调用名为$.trim的工具函数,能删除字符串中左右两边的空格符,但该函数不能删除字符串中间的空格,调用格式为:

$.trim (str);

参数str表示需要删除左右两边空格符的字符串。

例如,通过$.trim()函数,除掉一个两边均有空格符的字符串,并将其执行前后的字符长度都显示在页面中,如下图所示:

在浏览器中显示的效果:

从图中可以看出,由于文本框中的字符串前后分别有一个空格字符,因此,它的字符长度为13,调用trim()函数删除字符串前后空格之后,字符串长度则变为11。

任务

我来试试,亲自调用trim()函数删除字符串前后的空格。

在下列代码的第29行,调用trim()工具函数,删除文本输入框中字符串的前后空格。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>字符串操作函数</title>
  5. <link href="style.css" rel="stylesheet" type="text/css" />
  6. <script src="http://www.imooc.com/data/jquery-1.8.2.min.js" type="text/javascript"></script>
  7. </head>
  8.  
  9. <body>
  10. <div id="divtest">
  11. <div class="title">
  12. <span class="fl">字符串操作函数</span>
  13. <span class="fr">
  14. <input id="btnShow" name="btnShow" type="button" value="计算" />
  15. </span>
  16. </div>
  17. <div class="content">
  18. <input id="txtName" name="txtName" type="text" />
  19. <div class="tip"></div>
  20. </div>
  21. </div>
  22.  
  23. <script type="text/javascript">
  24. $(function () {
  25. $("#btnShow").bind("click", function () {
  26. $(".tip").html("");
  27. var strTmp = "内容:";
  28. var strOld = $("#txtName").val();
  29. var strNew =?;
  30. strTmp += strOld;
  31. strTmp += "<br/><br>除掉空格符前的长度:"
  32. strTmp += strOld.length;
  33. strTmp += "<br/><br>除掉空格符后的长度:"
  34. strTmp += strNew.length;
  35. $(".tip").show().append(strTmp);
  36. });
  37. });
  38. </script>
  39. </body>
  40. </html>
  1. #divtest
  2. {
  3. width: 282px;
  4. }
  5. #divtest .title
  6. {
  7. padding: 8px;
  8. background-color: Blue;
  9. color: #fff;
  10. height: 23px;
  11. line-height: 23px;
  12. font-size: 15px;
  13. font-weight: bold;
  14. }
  15. #divtest .content
  16. {
  17. padding: 8px;
  18. background-color: #fff;
  19. font-size: 13px;
  20. }
  21. #divtest .content .tip
  22. {
  23. border: solid 1px #ccc;
  24. background-color: #eee;
  25. margin: 20px 0px;
  26. padding: 8px;
  27. display: none;
  28. }
  29. .fl
  30. {
  31. float: left;
  32. }
  33. .fr
  34. {
  35. float: right;
  36. }
下一节