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

515 阅读2分钟

前言

之前总结了数组常用的方法,今天总结一下常用的操作字符串的方法~一起来看看都有哪些吧!


一、字符串定义

js中单引号或者双引号包裹起来的就是字符串

const str = 'hello'
const username = "Leo"

二、常用方法

1. str.length

可以得到字符串的长度 代码如下(示例):

let username = 'leo'

console.log(username.length) // 3

2. charAt()

传入一个索引值,就可以得到索引值所对应的字符 代码如下(示例):

let str = 'Hi~ Leo'

console.log(str.charAt(4)) // L

:空格也算一个字符

3. concat()

用于连接两个字符串 代码如下(示例):

let str = 'Hi~'
let username = 'Leo'

console.log(str.concat(username)) // Hi~Leo

4. includes()

用于检查某一字符串中是否包含某一段字符串,会返回一个布尔值 代码如下(示例):

const str = 'Hello Leo'

console.log(str.includes('Leo')) // true

5. match()

括号内写正则表达式,字符串调用这个方法后,通过正则校验后会返回一个数组,未通过返回null 代码如下(示例):

let username = 'Leo'
let userName = 'leo1'
// 匹配大小写字母开头的正则
const reg = /^[a-zA-Z]+$/

console.log(username.match(reg)) // ["Leo", index: 0, input: "Leo", groups: undefined]
console.log(userName.match(reg)) // null

6. replace()

可以把字符串中第一个符合要求的字符修改为指定字符 代码如下(示例):

let tel = '134 1234 1234'

console.log(tel.replace(' ','-')) // 134-1234 1234

7. replaceAll()

可以把字符串中所有符合要求的字符替换为指定字符 代码如下(示例):

let tel = '134 1234 1234'

console.log(tel.replaceAll(' ','-')) // 134-1234-1234

8. split()

括号内传入要以什么字符分割,最终返回一个数组,可以通过下标取出对应的字符串 代码如下(示例):

const hello = "Hello World";
const helloWorldSplit = hello.split(' ');

console.log(helloWorldSplit); // ["Hello", "World"];
console.log(helloWorldSplit[0]); // "Hello"

9. substring()

传入两个参数,分别是截取的其实索引和截取的终止索引 代码如下(示例):

const hello = 'Hello World';

console.log(hello.substring(1, 4)); // ell

:终止索引字符截取不到,不传第二个参数,默认截取至最后一个字符

10. toLowerCase()/toUppercase()

将字符串转变大小写 代码如下(示例):

const username = 'Leo'

console.log(username.toLowerCase()) // leo
console.log(username.toUpperCase()) // LEO

11. trim()

去除字符串左右两端的空白字符,对字符串中间的空格无效 代码如下(示例):

const username = '  le o  '

console.log(username.trim()) // le o

12. indexOf()

找到指定字符串在字符串中首次出现的索引值起始位置 代码如下(示例):

const str = 'Hi~ My name is Leo,nice to meet you~'

console.log(str.indexOf('Leo')) // 15

总结

今天就总结到这里~掰掰