js字符串对象方法

一些字符串对象的方法,内有注释

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>字符串对象</title>
</head>
<body>
    <script>
        var str  = 'we are dha hdashdfio aljd shidh aoi chain';
        var res = str.toUpperCase();
        console.log(res);   //返回全部字母大写
        console.log(str);

        res = res.toLowerCase();
        console.log(res);   //返回全部字母小写

        res = str.indexOf('a');
        console.log(res);   //3 返回第一次出现的索引

        res = str.lastIndexOf('a');
        console.log(res);   //38 返回第一次出现的索引

        res = str.indexOf('e',2);
        console.log(res);   //5 返回下表为2后第一次出现的'e'

        res = str.length;   
        console.log(res);   //41 返回字符串长度

        res = str.charAt(39);
        console.log(res);   //i 返回目标索引的值

        str  = 'we are dha hdashdfio aljd shidh aoi chain dha';
        res = str.search('dha');
        console.log(res);   //7 返回指定字符串第一次出现的位置

        res = str.slice(4,8);
        console.log(res);   //re d以[4,8)方式返回切片值,可以用负值,返回切片值

        res = str.substring(4,8);
        console.log(res);   //re d以[4,8)方式,不能用负值下标

        res = str.substr(4,8);
        console.log(res);   //re dha h 第一个值4是起始索引,第二个值8是切片长度

        str = "Please visit Microsoft and Microsoft!";
        res = str.replace("Microsoft", "W3School");//用另一个值替换在字符串中指定的值,只替换首个匹配,返回替换结束的整句话
        console.log(res);
        
        str = "Please visit Microsoft!";
        res = str.replace("MICROSOFT", "W3School");//对大小写敏感,不匹配
        console.log(res);   //==>Please visit Microsoft!

        //使得对大小写敏感,用正则表达式/i
        str = "Please visit Microsoft!";
        res = str.replace(/MICROSOFT/i, "W3School");  //可以匹配并且替换
        console.log(res);   //==>Please visit W3School!

        //替换所有匹配的值
        str = "Please visit Microsoft and Microsoft!";
        res = str.replace(/Microsoft/g,'W3School');
        console.log(res);   //Please visit W3School and W3School!

        var text1 = "Hello";
        var text2 = "World";
        res = text1.concat(' ',text2);
        console.log(res);   //Hello World  连接字符串

        str = "       Hello World!        ";
        res = str.trim();
        console.log(res);   //去除字符串两侧的空格

        var txt = "a,b,c,d,e";
        res = txt.split(',');
        console.log(res);//['a', 'b', 'c', 'd', 'e'] 以','为分割转成数组

        res = txt.split(' ');
        console.log(res);   //['a,b,c,d,e']  以空格分割
    </script>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值