zoukankan      html  css  js  c++  java
  • js去掉字符串前后空格的五种方法

    第一种:循环检查替换

    Js代码  收藏代码
    1. //供使用者调用    
    2. function trim(s){    
    3. return trimRight(trimLeft(s));    
    4. }    
    5. //去掉左边的空白    
    6. function trimLeft(s){    
    7. if(s == null) {    
    8. return "";    
    9. }    
    10. var whitespace = new String("  ");    
    11. var str = new String(s);    
    12. if (whitespace.indexOf(str.charAt(0)) != -1) {    
    13. var j=0, i = str.length;    
    14. while (j < i && whitespace.indexOf(str.charAt(j)) != -1){    
    15. j++;    
    16. }    
    17. str = str.substring(j, i);    
    18. }    
    19. return str;    
    20. }    
    21. //去掉右边的空白 www.2cto.com     
    22. function trimRight(s){    
    23. if(s == null) return "";    
    24. var whitespace = new String("  ");    
    25. var str = new String(s);    
    26. if (whitespace.indexOf(str.charAt(str.length-1)) != -1){    
    27. var i = str.length - 1;    
    28. while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1){    
    29. i--;    
    30. }    
    31. str = str.substring(0, i+1);    
    32. }    
    33. return str;    
    34. }   


    第二种 :正则替换

    Js代码  收藏代码
    1. <SCRIPT LANGUAGE="JavaScript">    
    2. <!--    
    3. String.prototype.Trim = function()    
    4. {    
    5. return this.replace(/(^s*)|(s*$)/g, "");    
    6. }    
    7. String.prototype.LTrim = function()    
    8. {    
    9. return this.replace(/(^s*)/g, "");    
    10. }    
    11. String.prototype.RTrim = function()    
    12. {    
    13. return this.replace(/(s*$)/g, "");    
    14. }    
    15. //-->    
    16. </SCRIPT>   

     



    第三种:使用jquery

    Js代码  收藏代码
    1. $.trim(str)   
    2. jquery内部实现为:  
    3. [javascript]  
    4. function trim(str){     
    5.     return str.replace(/^(s|u00A0)+/,'').replace(/(s|u00A0)+$/,'');     
    6. }     

     


    第四种:使用motools

    Js代码  收藏代码
    1. function trim(str){     
    2.     return str.replace(/^(s|xA0)+|(s|xA0)+$/g, '');     
    3. }    

    第五种:裁剪字符串方式 

    Js代码  收藏代码
    1. function trim(str){     
    2.     return str.replace(/^(s|xA0)+|(s|xA0)+$/g, '');     
    3. }    

     


    经过测试第五种方法在处理长字符串时效率最高。

  • 相关阅读:
    Day 03
    Day 03 作业
    Day 02 作业
    Day 02
    Day 01
    Day 10 面向对象基础
    Spring学习-- Bean 的作用域
    一、基本知识
    cloud-init使用技巧
    如何在KVM中管理存储池
  • 原文地址:https://www.cnblogs.com/mrxia/p/3804028.html
Copyright © 2011-2022 走看看