0
点赞
收藏
分享

微信扫一扫

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 条评论