js字符串的常用方法

charAt

charAt(索引)是找到指定位置的内容并返回,如果没有对应的索引,那么返回空字符串

var str = 'Jack'

// 使用 charAt 找到字符串中的某一个内容
var index = str.charAt(2)

console.log(index) // c

charCodeAt

charCodeAt(索引)返回对应索引位置的unicode编码

var str = 'Jack'

// 使用 charAt 找到字符串中的某一个内容
var index = str.charCodeAt(0)

console.log(index) // 74

indexOf

indexOf就是按照字符找到对应位置的索引

var str = 'Jack'

// 使用 indexOf 找到对应的索引
var index = str.indexOf('J')

console.log(index) // 0

substring

substring是用来截取字符串使用的
语法:substring(从哪个索引开始,到哪个索引为止),包含开始索引,不包含结束索引

var str = 'hello'
//         01234

// 使用 substring 截取字符串
var newStr = str.substring(1, 3)

console.log(newStr) // el

substr

substr也是用来截取字符串
语法:substr(从哪个索引开始,截取多少个)

var str = 'hello'
//         01234

// 使用 substr 截取字符串
var newStr = str.substr(1, 3)

console.log(newStr) // ell

toLowerCase 和 toUpperCase

用于将字符串字母转为小写或大写

var str = hello

// 使用 toUpperCase 转换成大写
var upper = str.toUpperCase()

console.log(upper) // HELLO

// 使用 toLowerCase 转换成小写
var lower = upper.toLowerCase()

console.log(lower) // hello

repeat

重复字符串,返回新字符串

var str = hello
console.log(str.repeat(4))//hellohellohellohello

猜你喜欢

转载自blog.csdn.net/horizon12/article/details/108348940