字符串方法

79 阅读3分钟

slice(startIndex,endIndex) 剪切字符,返回新字符

  • 不包括endIndex的字符
  • 原字符不变
  • 第二个参数如没有,切剩余全部
  • 第二个参数如为负数,表示尾端切掉几个
const str = 'abced'
console.log(str.slice(1,2)) // b
console.log(str.slice(1)) // bced
console.log(str.slice(1,-1)) // bce -1尾部切掉1个

substr(startIndex,count) 剪切字符,返回新字符

  • 原字符不变
  • 第二个参数没有,返回全部剩余字符
    const str = 'abced'
    console.log(str.substr(1,2), str) // bc abced
    console.log(str,substr(1)) // bced

substring(startIndex,endIndex) 剪切字符,返回新字符

  • 原字符不变
  • 不包括endIndex字符
  • 剪切个数为endIndex-startIndex
  • 如果endIndex小于startIndex,会交换位置
  • 不接受负数
    const str = 'abced'
    console.log(str.substring(1,3)) // bc
    console.log(str.substring(3,1)) // bc

chartAt(index) 返回字符

    console.log('abc'.charAt('1')) // b

indexOf('') lastIndexOf('') 返回索引

  • indexOf 从左到右找
  • lastIndexOf 从右到左找
'abc'.indexOf('b') // 1
'abcc'.lastIndexOf('c') // 3

concat('') 返回新字符串

    console.log("abc".concat("ef")) // abcef

split('') 返回数组

  • 原字符不变
console.log("a*b*c".split("*")) // ['a', 'b', 'c']
console.log('abc'.split()) // ['abc']

toLowerCase() 返回小写字符串

  • 原字符不变
    const str = "AbC"
    console.log(str.toLowerCase(), str) // abc Abc

toUpperCase() 返回大写字符串

  • 原字符不变
    const str = "AbC"
    console.log(str.toUpperCase(), str) // ABC Abc

includes('') 返回布尔

  • 返回布尔值
    const str = 'abced'
    console.log(str.includes('b')) // true

startsWith('') 返回布尔

  • 是否以什么字符开始
console.log('abc'.startsWith('a')) // true

endsWith('') 返回布尔

  • 是否以什么字符结束
console.log('abc'.endsWith('a')) // false

trim() 返回新字符串

  • 去掉头尾空格,中间不去
console.log(' 1 23  '.trim()) // '1 23'

repeat(number) 返回新字符串

  • 重复几次
console.log('abc'.repeat(2)) // abcabc

match(正则/指定字符) 返回数组

const str = "2018年结束了,2019年开始了,2020年就也不远了"
console.log(str.match("20")) // 返回看不懂,是个数组
console.log(str.match(/\d+/g)) // 匹配所有数字 ['2018', '2019', '2020']

replace(被替换字符/正则,替换字符/回调函数) 返回新字符串

  • 原字符不变
  • 如果第一个参数为字符串,只能匹配第一个
const str = "2018年结束了,2019年开始了,2020年就也不远了"
console.log(str.replace("20", "?"), str) // ?18年结束了,2019年开始了,2020年就也不远了
console.log(str.replace(/\d+/g, "!"))  // !年结束了,!年开始了,!年就也不远了
const rs = str.replace(/\d+/g, function (item) {
  return "?"
})
console.log(rs) // ?年结束了,?年开始了,?年就也不远了

search(正则) 返回索引

  • 返回匹配正则的第一个索引
const str = "2018年结束了,2019年开始了,2020年就也不远了"
console.log(str.search(/\d+/g)) // 0

字符转义

  • 判断空格,正则匹配str.replace(/ /g, "?") 空格都替换为问号
  • 定义带有换行的字符用`` 不是普通的单双引号。
  • ':单引号
  • ":双引号
  • \:反斜杠
  • \n:换行
  • \r:回车
  • \t:制表符
  • \b:退格
  • \f:换页
let str = "这是一个包含\"双引号\"的字符串";
console.log(str); // 输出:这是一个包含"双引号"的字符串
const str = `abc
  sfsdf
  ddf
            ` // 注意这里的定义符号
console.log(str) // 同str格式
console.log(JSON.stringify(str).replace(/ /g, "\?")) // "abc\n??sfsdf\n??ddf\n????????????"