JavaScript常用字符串处理

常用字符串处理

let str = "Hello world!";

// 返回某个指定的字符串值在字符串中首次出现的位置,不存在则返回-1    lastIndexOf()
console.log(str.indexOf("e")) // 1 

// 检索查询相匹配的字符串的起始位置或正则,能匹配则返回位置,没有匹配则返回-1
console.log(str.search("w")) // 6
console.log(str.search(new RegExp("world"))) // 6

// 检索查询相匹配的字符串的起始位置或正则,能匹配则返回匹配内容,没有匹配则返回null
console.log(str.match('He')) // "He"
console.log(str.match(new RegExp("world"))) // “world”

// 正则检验字符串,能匹配则返回true,没有匹配则返回false
console.log(new RegExp("world").test(str)); // true

// 返回指定位置的字符,即index=4的字母
console.log(str.charAt(4)) // o  

// 提取字符串的某个部分,提取1-4 不含4
console.log(str.slice(1, 4)) // ell  

// 把一个字符串分割成字符串数组
console.log(str.split("")) // ["H", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]
console.log(str.split(" ")) // ["Hello", "world!"]

// 提取字符串中介于两个指定下标之间的字符,如果是负数,将被替换成0   (起始位置,结束位置)
console.log(str.substring(1)) // ello world!  1到字符串末尾全部截取
console.log(str.substring(1, 4)) // ell  提取1-4 不含4       

// 提取字符串下标开始的指定数目的字符  (起始位置,长度)
console.log(str.substr(1)) // ello world!  1到字符串末尾全部截取
console.log(str.substr(1, 4)) // ello  提取从1开始4个字符
   
// 将lo替换成555  
console.log(str.replace('lo', 555)) // Hel555 world!  

// 将两个或多个字符的文本组合起来
console.log(str.concat("Hello JavaScript!")) // Hello world!Hello JavaScript!

// 删除前后空格
console.log("   Hello world!   ".trim())

// 转小写
console.log(str.toLowerCase()) // hello world!  

// 转大写
console.log(str.toUpperCase()) // HELLO WORLD!  

substring与substr区别

.

substring(start,end)

substring 方法返回字符串中介于两个指定下标之间的字符。(包括 start ,但不包括 end 处的字符)

str.substring(1, 4) // 这里与 str.slice(1, 4) 一样  =>  ell   

如果 start 与 end 相等,那么该方法返回的就是一个空串(即长度为 0 的字符串)。

str.substring(2, 2) // ""

如果 start 比 end 大,那么该方法在提取子串之前会先交换这两个参数。

str.substring(5, 1)  //  str.substring(1, 5)  => ello

如果 start 或 end 为负数,那么它将被替换为 0。

str.substring(2, -1)  //  str.substring(0, 2)  =>  He

.

substr(start,length)

substr 方法返回字符串下标开始的指定数目(长度)的字符

str.substr(1, 4) // ell0

如果start为负数,则start=str.length+start。

str.substr(-2, 1) // d

如果 length 为 0 或负数,将返回一个空字符串。

str.substr(2, 0) // ""
str.substr(2, -2) // ""
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猫老板的豆

你的鼓励将是我创作的最大动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值