JS 字符串

2016-11-04  本文已影响0人  王难道

常见的字符串方法

1.长度计算,连接

    var str = "hello";
    console.log( str.length );
    console.log( str[0] );
    console.log( str[str.length - 1]  );
    console.log( str.charAt(0) );
    console.log( str.charCodeAt(0) );

    var str2 = " world";
    var str3 = str1 + str2;
    cosnole.log( str3 );

2.字符串截取

    var str = "hello world";
    var sub1 = str.substr(1, 3); // 第一个是开始位置, 第二个是长度
    var sub2 = str.substring(1, 3); // 第一个是开始位置,第二个是结束位置,长度为第二个-第一个
    var sub3 = str.slice(1, 3); // 同上 允许负参

3.字符串分割

stringObject.split(separator,howmany)

4.查找

    var str = "hello my world";
    var s1 = str.search('my');//6 找不到为-1
    var s2 = str.replace('my', 'your');
    //hello your world
    var s3 = str.match('my'); 
    //["my", index: 6, input: "hello my world"]

5.大小写

    var str = "Hello";
    str.toUpperCase();
    str.toLowerCase();

本教程版权归饥人谷和作者所有,转载须说明来源。

上一篇 下一篇

猜你喜欢

热点阅读