javascript string常用api

76 阅读2分钟

.starsWith() | .endsWith()

  • str.startWith(searchString[, position])在str中以position为开始位置搜索searchString,判断str是否以searchString开头,返回true或false
const str = 'to be, or not to be'
str.startsWith('to be') // true
str.startsWith('not') // false
str.startsWith('not', 10) // true
  • str.endWith(searchString[, length])截取str中长度为length的字符串,判断它是否以searchString结尾
const str = 'to be, not to be, that is the question'
str.endsWith('question') // true
str.endsWith('to be') // false
str.endsWith('to be', 19) // true

.trim() | .trimEnd() | .trimStart() | .padEnd() | .padStart()

  • str.trim()从字符串的两端清除空格,返回一个新的字符串,不修改原字符串
const str = '  name   '
str.trim() // 'name'
  • str.trimEnd()从字符串的末尾清除空格,返回一个新的字符串,trimRight()是它的别名
const str = '   name  '
str.trimEnd() // '   name'
  • str.trimStart()从字符串的开头清除空格,返回一个新的字符串,trimLeft()是它的别名
const str = '   name  '
str.trimStart() // 'name  '
  • str.padEnd(targetLength, padString)用padString从str字符串末尾开始填充到字符串中(可重复填充),返回填充后达到targetLength长度的字符串
let str = 'abc'
str.padEnd(6) // 'abc   '
str.padEnd(10, 'foo') // 'abcfoofoo'
str.padEnd(6, '123456') // 'abc123' 填充后字符串长度超过目标长度,只保留左侧部分
str.padEnd(1) // 'abc' 目标长度小于当前字符串长度,返回原字符串
  • str.padStart(targetLength, padString)用padString从str字符串开头开始填充到字符串中(可重复填充),返回填充后达到targetLength长度的字符串
let str = 'abc'
str.padStart(6) // '   abc'
str.padStart(10, 'foo') // 'foofooabc'
str.padStart(6,'123456') // '123abc'

.charAt() | .charCodeAt() | .codePointAt()

  • str.charAt(index)从str中返回索引值为index的字符
const str = 'abcdefg'
str.charAt(3) // 'd'
str.charAt(99) // ''
  • str.charCodeAt(index)返回0~65535之间的整数,表示给定索引处的UTF-16代码单元
const str = 'abc'
str.charCodeAt(0) // 97
str.charCodeAt(1) // 98
str.charCodeAt(2) // 99
str.charCodeAt(3) // NaN
  • str.codePointAt(pos)返回字符串中pos位置元素的Unicode编码点值的非负整数
const str = 'abc'
str.codePointAt(0) // 97
str.codePointAt(5) // undefined

String.fromCharCode() | String.fromCodePoint() | String.raw()

  • String.fromCharCode(num1[, ...[, numN]])返回指定UTF-16代码单元序列创建的字符串,num1,...numN是UTF-16代码单元的数字,范围0~65535(0xFFFF)
String.fromCharCode(97,98,99) // 'abc'
  • String.fromCodePoint(num1[, ...[, numN]])返回使用指定的代码点序列创建的字符串
String.fromCodePoint(97) // 'a'
String.fromCodePoint(-1) // RangeError
  • String.rawtemplateString获取一个模板字符串的原始字符串
let name = 'foo'
String.raw`hi ${name}` // 'hi foo'