zoukankan      html  css  js  c++  java
  • js去掉字符串前后空格三种方法及最佳方案

    第一种:非正则表达式循环检索--在长的头尾空格字符串中使用效率较低

     1 if(!String.prototype.trim){
     2   String.prototype.trim = function(){
     3         var start = 0,
     4             end = this.length - 1,
     5             //包括ECMAScript5中定义的所有空白字符
     6             ws = "\n\r\t\f\x0b\xa0\u1680\u180e
     7             \u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009
     8             \u200a\u200b\u2028\u2029\u202f\u205f\u3000\ufeff";
     9         while(ws.indexOf(this.charAt(start))>-1){
    10             start++;
    11         }
    12         while(end>start && ws.indexOf(this.charAt(end))>-1){
    13             end--;
    14         }
    15         return this.slice(start,end+1);
    16     }
    17 }

     第二种:利用正则表达式--在去除尾空格时效率比较低

    1 if(!String.prototype.trim){
    2     String.prototype.trim = function() 
    3     { 
    4         return this.replace(/^\s+/,"").replace(/\s+$/,"");
    5     }
    6 }

    第三种:最佳方法:用正则表达式除去头部空格,用非正则表达式去除尾部空格

     1 if(!String.prototype.trim){
     2   String.prototype.trim = function(){
     3         var str = this.replace(/^\s+/,""),
     4             end = this.length - 1,
     5             ws = /\s/;
     6             while(ws.test(this.charAt(end))){
     7                 end--;
     8             }
     9             return this.slice(0,end+1);
    10     }
    11 }
  • 相关阅读:
    第31-35课
    Cisco学习笔记
    ScreenOS地址转换
    Bootstrap3组件--2
    Bootstrap3组件--1
    Bootstrap3全局CSS样式
    MySQL数据库中字段含逗号的数据,分隔成多条数据
    EF Core 关联数据
    ABP 创建 webapi
    Abp ajax The required antiforgery request token was not provided in either form field
  • 原文地址:https://www.cnblogs.com/leolai/p/2549115.html
Copyright © 2011-2022 走看看