JS中字符串常用的方法总结

JS中字符串常用的方法总结

声明:所有字符串方法都会返回新的字符串,不会修改原始字符串

文章内的代码结果演示有部分res本身是字符串,但是通过console输出显示结果注释中我没带双引号,所以勿喷哈哈哈~~

1. length 返回字符串的长度
let res=str.length('123')
console.log(res)  //3
2. indexof( ) 返回指定文本首次出现的索引(位置)
lastIndexOf( ) 返回指定文本首次出现的索引

上述两个方法若都找不到,返回-1,同时接受传递第二个参数,用来从起始位置开始检索

let str="hello"
let res1=str.indexOf("h")
let res2=str.lastIndexOf("l")
console.log(res1,res2)  //0  3
3.search( ) 用于搜索特定的字符串,并返回其匹配位置,但无法传递第二个参数
let str="hello world"
let res=str.search("hel")
console.log(res)  //0
4.slice(m,n ) 从索引m开始提取字符串到n处,包括索引m不包括索引n,返回的是个新的字符串 参数2不传,表示直接到最后,若参数为负,表示直接从结尾处开始计数
let str="helloworld"
let res=str.slice(3) 
let res1=str.slice(3,5)
console.log(res,res1)  //loworld    lo 
5.与slice( )类似的两个方法
substring( ) 接收不了负索引 ,参数2不传,表示直接到最后
substr( ) 第二个参数为被提取部分的长度
let str="helloworld"
let res=str.substring(3) 
let res1=str.substr(3,5)
console.log(res,res1)  //loworld   lowor
6.replace( ) 用后者替换在字符串中指定的值,返回的是新字符串,注意:该方法中对大小写敏感
let str="helloworld"
let res=str.replace("hello","my") 
let res1=str.replace("HELLO","my")
console.log(res,res1)  //myworld  helloworld
7. toUpperCase( ) 对字符串中每个字符转大写
toUpperCase( ) 对字符串中每个字符转小写
8. concat( ) 连接两个或者多个字符串
let str="123"
let res=str.concat("hel","lo")
console.log(res) // 123hello
9. String.trim( ) 删除字符串两端的空白
let str="   hello   "
let res=str.trim()
console.log(res)  // hello
10.charAt( ) 返回字符串中指定下标的字符串
charCodeAt( ) 返回指定索引的字符unicode编码值
let str="beautiful"
let res=str.charAt(4)
console.log(res)  // t
11.split( ) 将字符串转为数组,支持传递一个字符串作为分隔符,不传默认逗号为分隔符
let str="bea,ut,iful"
let res=str.split(",")
console.log(res)   // ["bea", "ut", "iful"]

好了,本期分享到此结束,欢迎大家在下方留言评论,一起学习交流呀,附上一张温柔的背景图。**** &&小屋Niki
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值