JavaScript: 字符串

风行水上 @ 2010-12-07 16:02:15
标签:

    单引号和双引号

    我们都知道字符串用是用单引号或双引号括起来的。在别的语言中(比如PHP),通常双引号允许转义字符,单引号则不允许转义字符。而在JavaScript中,事实上单引号和双引号的作用是完全一样的。

    var s1 = "This is a \"string\"\nhaha";
    var s2 = 'This is a \"string\"\nhaha';
    

    上面例子中两个字符串完全等效。

    字符串是文本(literal)还是对象(object)

    字符串有两种形态:String Object和String Literal。

    var s1 = "This is a string Literal"; 
    var s2 = new String("This is a string object");  
    alert(typeof s1);           // typeof(s1)=='string' , Literal
    alert(typeof s2);           // typeof(s1)=='object' , Object
    alert(typeof s2.valueOf()); // "string", Literal
    

    String.valueOf()回返回字符串的原始形态(Primitive Value)。

    字符串是按值传递(by value)还是按地址传递(by reference)

    var s1 = "abc", s2 = new String("def");
        
    function modify_it(ts1, ts2) {
      ts1 += '...';  ts2 += '...';
    }
    modify_it(s1,s2);
    alert(s1+"\n"+s2);  // 字符串内容没有被改变
    

    可见字符串是按值传递的。

    长字符串的处理

    下面是几种处理长字符串的方法。

    • Concatenation: 利用 '+' 号,主要问题是效率低。
    • Line Continuation: 直接定义,效率最好。除了要在每行末尾加反斜线 '\'
    • Array: 利用数组的join()方法,效率比‘+’ 略好。动态生成字符串时可以考虑。
    // Concatenation 
    var s1 = 'abc '
           + 'def';
    
    // Line Continuation 
    var s2 = 'abc \
    def';
    
    var s3 = "abc \
    def\
    ";
       
    // Array
    var s4 = ['abc','def'].join(' ');                 
    

    数字显示为字符

    // 显示小数点后两位
    
    number.toFixed(12345.7890);  // 返回:12345.78
    
    function commafy(num) {
      var str = (num+"").split("."),
      dec=str[1]||"",
      num=str[0].replace(/(\d)(?=(\d{3})+\b)/g,"$1,");
      return (dec) ? num+'.'+dec : num;
    }
    
    commafy(12345.7890); // 返回:12,345.7890
    

    一些有用的原型函数 (prototype function)

    • trim() : 去除首尾空白字符
    • ltrim(): 去除开头的空白字符
    • rtrim(): 去除结尾的空白字符
    • htmlEntities() : 转义HTML特殊字符
    • stripTags() : 去除HTML标签
    String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g,'');}
    String.prototype.ltrim = function(){return this.replace(/^\s+/g,'');}
    String.prototype.rtrim = function(){return this.replace(/\s+$/g,'');}
    String.prototype.htmlEntities = function () {
       return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
    };
    String.prototype.stripTags = function () {
       return this.replace(/<([^>]+)>/g,'');
    }
    

    网络资源

    标签:

      分享到:
      comments powered by Disqus

      20/22ms