字符串的方法

1.charAt( )

  得到指定下标的字符

   这个会被  ' 我喜欢js,我也喜欢HTML '[1] = 得到喜

例子:

            var str = '我喜欢js,我也喜欢HTML'
            
            console.log('下标为0:' + str.charAt(0)); 
            // 下标为0:我
            
            console.log('下标为-1:' +str.charAt(-1));
            // 下标为-1:
            
            console.log('下标为5:' +str.charAt(5));
            // 下标为5:,
            
            console.log('下标为7:' +str.charAt(7));
            // 下标为7:也

 

 

2.substring( a,b )

  得到子串

    a是下标,b也是下标

    1:从a开始到b结束( 不包括b )的子串

    2:如果省略第二个参数(b),那么就得到剩下的全部

    3:a可以大于b,会自动调整大的数在后面

 

例子:

            var str = '我喜欢js,我也喜欢HTML'
            
            console.log('得到1方法:' + str.substring(3,5)); 
            // 得到1方法:js
            
            console.log('得到2方法:' +str.substring(6));
            // 得到2方法:我也喜欢HTML
            
            console.log('得到3方法:' +str.substring(5,3));
            // 得到3方法:js

 

3.substr( a,b )

  得到子串

    a表示下标,也可以为负数(-1 : 就是倒数第一个,0是正数第一个);

    b表示个数;

     都是从前往后数的,超过最后一个的话,就不算的了!!!看第三个例子

例子:

            var str = '我喜欢js,我也喜欢HTML'
            
            console.log('得到:' + str.substr(3,5)); 
            // 得到:js,我也
            
            console.log('得到:' +str.substr(6));
            // 得到:我也喜欢HTML
            
            console.log('得到:' +str.substr(-3,5));
            // 得到:TML

 

4.slice( a,b )

  得到子串

    a是下标,b是下标

    a可以为负数(-1 : 就是倒数第一个,0是正数第一个);

    从a开始到b结束( 不包括b )的子串

    如果省略第二个参数(b),那么就得到剩下的全部

    a必须小于b( 只能按顺序排,不能反过来 )

 

例子:

       var str = '我喜欢js,我也喜欢HTML'
            
            console.log('得到:' + str.slice(3,5)); 
            // 得到:js
            
            console.log('得到:' +str.slice(-3,-5));
            // 得到(只能按顺序排,不能反过来):空
            
            console.log('得到:' +str.slice(-3,-1));
            // 得到:TM
            
            console.log('得到:' + str.slice(5,3));
            // 得到(因为a必须小于b,也就是 只能按顺序排,不能反过来):空
            
            console.log('得到:' +str.slice(6));
            // 得到:我也喜欢HTML

 

 

 

 5.toUpperCase( )  字符串变为大写

 

 6.toLowerCase( )  字符串变为大写

 

 7.indexOf( ) 检索字符串

  ( ) 里面填写的是字符串(填写多个也要匹配上,但是得到第一个的下标,如果匹配不上就-1),得到的是首次找到该字符的下标的值,  找不到的话,就返回 -1

            var str = '我喜欢js,我也喜欢HTML'
            
            console.log('得到:' + str.indexOf(',')); 
            // 得到: 5
                    
            console.log('得到:' +str.indexOf('我'));
            // 得到: 0
            
            console.log('得到:' +str.indexOf('L'));
            // 得到: 13
            
            console.log('得到:' +str.indexOf('我喜欢'));
            // 得到: 0

        console.log('得到:' +str.indexOf('我不喜欢'));
        // 得到: -1

            console.log('得到:' +str.indexOf('ET'));
            // 得到: -1

 

posted @ 2022-01-10 09:23  杨建鑫  阅读(82)  评论(0编辑  收藏  举报