实用的 JavaScript 字符串内置方法
XPoet 自由程序猿

在 JavaScript 中,字符串是一种常用的数据类型,作为我们开发人员使用最频繁的数据类型之一,本文介绍一些你可能不太了解但又非常实用的字符串内置方法,帮助你提升开发效率,快速完成数据处理。

charAt(index)

返回指定索引位置的字符。

1
2
3
const str = 'Hello, World'
const char = str.charAt(7)
console.log(char) // 输出:W

charCodeAt(index)

返回指定索引位置字符的 Unicode 编码。

1
2
3
const str = 'Hello, World'
const charCode = str.charCodeAt(7)
console.log(charCode) // 输出:87

concat(str1, str2, …)

连接两个或多个字符串。

1
2
3
4
const str1 = 'Hello'
const str2 = 'World'
const result = str1.concat(', ', str2, '!')
console.log(result) // 输出:Hello, World!

indexOf(searchValue, startIndex)

返回指定字符串在原字符串中首次出现的位置索引。

1
2
3
const str = 'Hello, World'
const index = str.indexOf('World')
console.log(index) // 输出:7

lastIndexOf(searchValue, startIndex)

返回指定字符串在原字符串中最后一次出现的位置索引。

1
2
3
const str = 'Hello, World'
const index = str.lastIndexOf('l')
console.log(index) // 输出:10

slice(startIndex, endIndex)

提取字符串的一部分,返回新字符串。

1
2
3
const str = 'Hello, World'
const sliced = str.slice(7, 12)
console.log(sliced) // 输出:World

substring(startIndex, endIndex)

slice 类似,提取字符串的一部分,返回新字符串。

1
2
3
const str = 'Hello, World'
const sub = str.substring(7, 12)
console.log(sub) // 输出:World

substr(startIndex, length)

提取字符串的一部分,返回新字符串,基于起始位置和长度。

1
2
3
const str = 'Hello, World'
const sub = str.substr(7, 5)
console.log(sub) // 输出:World

toUpperCase()

将字符串转换为大写。

1
2
3
const str = 'Hello, World'
const upper = str.toUpperCase()
console.log(upper) // HELLO, WORLD

toLowerCase()

将字符串转换为小写。

1
2
3
const str = 'Hello, World'
const lower = str.toLowerCase()
console.log(lower) // 输出:hello, world

replace(searchValue, replaceValue)

替换字符串中的指定值。

1
2
3
const str = 'Hello, World'
const replaced = str.replace('World', 'Universe')
console.log(replaced) // 输出:Hello, Universe

split(separator, limit)

将字符串拆分为子字符串数组。

1
2
3
const str = 'apple,orange,banana'
const fruits = str.split(',')
console.log(fruits) // 输出:['apple', 'orange', 'banana']

trim()

去除字符串两端的空格。

1
2
3
const str = '   Hello, World   '
const trimmed = str.trim()
console.log(trimmed) // 输出:Hello, World
 Comments
Comment plugin failed to load
Loading comment plugin