JavaScript常用的字符串操作 (包含ES6)

1,117 阅读3分钟

1、查找相关 (有索引)

  1. charAt() //返回在指定位置的字符。
var str="abc"
console.log(str.charAt(0))  //a
  1. charCodeAt() //返回在指定的位置的字符的 Unicode 编码。
var str="abc"
console.log(str.charCodeAt(1))//98

2、查找相关 (有字符串)

  1. indexOf() // 从前往后返回匹配到的字符串的索引起始的值 下标从0开始 查找不到则返回 -1 (number型) 识别大小写indexOf()
var str="Hello world!"
console.log(str.indexOf("Hello"))//0
console.log(str.indexOf("World"))//-1
console.log(str.indexOf("world"))//6
indexof()  第二个参数是你要查找到的开始位置,默认从索引0开始查找

2. lastIndexOf() // 从后往前查找 和indexOf一样

var str="hello world";
var n=str.lastIndexOf("l");
console.log(n) //9
n=str.lastIndexOf("l",4);
console.log(n) // 3
  1. replace(替换的字符串,替换的值) // 字符串替换
let s = '123456789'
let b = s.replace(/1/, '0')
console.log(b); // 023456789
console.log(s); // 123456789

3、字符串截取

  1. slice(start,end) // 从字符串中提取片段,不包含结尾,参数为字符串的索引位置
let s = '123456789'
let b = s.slice(0, 1)
console.log(b);  //1
  1. substr(start,length) // 从字符串中截取字符串,第二个参数为你要截取的长度
let s = '123456789'
let b = s.substr(2, 1)
console.log(b); // 3
  1. substring(start,end) // 他的用法和slice一样 只不过参数不接受负值
let s = '123456789'
let b = s.substring(01)
console.log(b); // 1

4、字符串处理(转换成数组,大小写转换,去除两边空格)

  1. toLowerCase() // 将字符串转换为小写
let s = 'DFDSSSssss'
let b = s.toLowerCase()
console.log(b); //dfdsssssss
console.log(s); //DFDSSSssss
  1. toUpperCase() // 将字符串转为大写
let s = 'DFDSSSssss'
let b = s.toUpperCase()
console.log(b); //DFDSSSSSSS
console.log(s); //DFDSSSssss
  1. trim() // 去除字符串两端的空白字符
let s = '       DFDSSSssss        '
let b = s.trim()
console.log(b); //DFDSSSssss
console.log(s); //       DFDSSSssss      
  1. split() // 将字符串分割为数组
let s = '123456789'
let b = s.split('')
console.log(b); // ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
console.log(s); //123456789
  1. concat() // 拼接几段字符串 返回新的字符串
let s = '123456789'
let b = s.concat('1', '000', '000')
console.log(b); // 1234567891
console.log(s); //1234567891000000
  1. repeat() // 将字符串重复几次 ES6
let s = '1'
let b = s.repeat(2)
console.log(b); // 11
console.log(s); //1
  1. padStart() // 将字符串开头以指定字符补全 ES6
let s = '1'
let b = s.padStart(5, 0)
console.log(b); // 
console.log(s); //1
  1. padEnd() // 将字符串开头以指定字符补全 ES6
let s = '1'
let b = s.padEnd(5, 0)
console.log(b); // 
console.log(s); //1

5、字符串判断

  1. startsWith() // 判断是否以指定字符串开头,返回结果为布尔值 ES6
let s = 'ab'
let b = s.startsWith('a')
console.log(b); //true
  1. endsWith() // 判断是否以指定字符串结尾,返回结果为布尔值 ES6
let s = 'ab'
let b = s.endsWith('b')
console.log(b); //true
  1. includes() // 判断当前字符串是否包含指定字符 ES6
let s = '123456789'
let b = s.includes('1')
console.log(b); // true
console.log(s); //123456789

整理不易,有问题请留言,如果可以,请为本文留下一个小赞。