字符串的一些方法简介

字符串方法

tip这个是我自己总结的,可能不全,可能有错(望指证),有兴趣的朋友可以去官网查看这些方法。

  1. length
  • 返回字符串的长度
 var str='jcidjfdsijfs';
        console.log(str.length);//12
  1. indexOf(searchVlue[,fromIndex])
  • 返回字符串在指定文本中第一次出现的索引,从fromIndex开始搜索,若未找到,则返回-1
        var str='hello world';
        console.log(str.indexOf("lo"));//3
        console.log(str.indexOf("lo",3));//-1
  1. lastIndexOf(searchVlue[,fromIndex])
  • 返回字符串在指定文本中最后一次出现的索引,若未找到,则返回-1
        var str='hello world';
        console.log(str.lastIndexOf("l"));//9
  1. search()
  • 执行正则表达式和String对象之间的一个搜索匹配,若匹配成功,则返回正则表达式在字符串中首次出现的匹配项的索引,否则返回-1
        var str="heLlo WoRld";
        var reg=/[A-Z]/g;
        console.log(str.search('lo'));//3
  1. 截取字符串的方法
  • slice(start,end)
    提取字符串的一部分,并返回一个新的字符串(从原来的字符串中提取出来的新字符串),且不会改变原来的字符串
        var str='hello world';
        console.log(str.slice(2,5));//llo
        console.log(str);//hello world
  • substring(start,end)
    方法返回一个字符串在开始索引到结束索引之间的一个子集,或从开始索引直到字符串的末尾的一个子集
        var str='hello world';
        console.log(str.substring(2,5));//llo
        console.log(str);//hello world
  • substr(start,length)
    返回一个字符串中从指定位置开始到指定字符数的字符
        var str='hello world';
        console.log(str.substr(2,5));//llo w
        console.log(str);//hello world
  1. replace()
  • 用另一个值来替换在字符串中的指定值,该方法不会改变原字符串
        var str='hello world';
        console.log(str.replace("hello","HELLO"));//HELLO world
        console.log(str);//hello world
  1. 字符串大小写转换
  • toUpperCase()将字符串转换为大写
  • toLowerCase()将字符串转换为小写
        var str='HELLO world';
        console.log(str.toUpperCase());//HELLO WORLD
        console.log(str);//HELLO world
        console.log(str.toLowerCase());//hello world
        console.log(str);//HELLO world
  1. concat()
  • 连接两个或者多个字符串
        var str1='hello';
        var str2='world';
        console.log(str1.concat(str2));//helloworld
  1. trim()
  • 去除字符串两端的空白字符
        var str='          hello world    '
        console.log(str.trim());//hello world
  1. charAt()
  • 返回字符串中指定下标的字符串
        var str='hello world';
        console.log(str.charAt(6));//w
        console.log(str);//hello world
  1. charCodeAt()
  • 返回字符串中指定索引的字符的unicode编码
        var str='hello world';
        console.log(str.charCodeAt(6));//119
  1. split()
  • 可以将字符串分割成为一个数组
        var str='hello world';
        console.log(str.split(''));//['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
        console.log(str.split('l'));//['he', '', 'o wor', 'd']
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值