跳到主要内容

String 字符串

属性

1. length 获得字符串长度

  • String 类型的 length 数据属性表示字符串的 UTF-16 码元长度。
const str = '你好,hello:'
console.log(`${str} ${str.length}`)
// output: "你好,hello: 9"

二,方法

1. at() 获得字符串对应 index 索引的那个字符

  • at() 方法接受一个整数值,并返回一个新的 String,该字符串由位于指定偏移量处的单个 UTF-16 码元组成。该方法允许正整数和负整数。负整数从字符串中的最后一个字符开始倒数。
语法:at(index)
const sentence = '中华人民共和国'
let index = 5
console.log(`index = ${index}${sentence.at(index)}`)
// output:"index = 5 是 和"

2. charAt()

  • String 的 charAt() 方法返回一个由给定索引处的单个 UTF-16 码元构成的新字符串。
  • charAt() 方法总是将字符串作为 UTF-16 码元序列进行索引,因此它可能会返回孤项代理。
  • 要获取给定索引处的完整 Unicode 码位,请使用 String.prototype.codePointAt() 和 String.fromCodePoint()。
语法:charAt(index)
const sentence = 'The quick brown fox jumps over the lazy dog.'
const index = 4
console.log(`The character at index ${index} is ${sentence.charAt(index)}`)
// Expected output: "The character at index 4 is q"

3. charCodeAt()

  • String 的 charCodeAt() 方法返回一个整数,表示给定索引处的 UTF-16 码元,其值介于 0 和 65535 之间。
  • charCodeAt() 方法总是将字符串当作 UTF-16 码元序列进行索引,因此它可能返回单独代理项(lone surrogate)。
  • 如果要获取给定索引处的完整 Unicode 码位,请使用 String.prototype.codePointAt() 方法。
语法:
const sentence = 'The quick brown fox jumps over the lazy dog.'
const index = 4
console.log(
`The character code ${sentence.charCodeAt(
index
)} is equal to ${sentence.charAt(index)}`
)
// output: "The character code 113 is equal to q"

4. codePointAt()

  • String 的 codePointAt() 方法返回一个非负整数,该整数是从给定索引开始的字符的 Unicode 码位值。
  • 请注意,索引仍然基于 UTF-16 码元,而不是 Unicode 码位。
语法:
const icons = '☃★♲'
console.log(icons.codePointAt(1))
// output: "9733"

5. concat() 连接字符串

  • concat() 方法将字符串参数连接到调用的字符串,并返回一个新的字符串。
语法:concat(str1),concat(str1, str2),concat(str1, str2, /* …, */ strN)
const str1 = 'Hello'
const str2 = 'World'
console.log(str1.concat(' aaa', str2))
// output: "Hello World"
console.log(str2.concat(', ', str1))
// output: "World, Hello"

6. endsWith() 判断某个字符是否在字符串结尾或特定位置结尾

  • endsWith() 方法用于判断一个字符串是否以指定字符串结尾,如果是则返回 true,否则返回 false。
语法:endsWith(searchString),endsWith(searchString, endPosition)
const str1 = '江山辈有人才出!'
console.log(str1.endsWith('出!'))
// output: true
console.log(str1.endsWith('人', 5))
// output: true
const str2 = 'Is this a question?'
console.log(str2.endsWith('出'))
// output: false

7. String.fromCharCode()

  • String.fromCharCode() 静态方法返回由指定的 UTF-16 码元序列创建的字符串。
语法:String.fromCharCode(num1, num2, /* …, */ numN)
console.log(String.fromCharCode(189, 43, 190, 61))
// output: "½+¾="

8. String.fromCodePoint()

  • String.fromCodePoint() 静态方法将根据指定的码位序列返回一个字符串。
语法:String.fromCodePoint(num1, num2, /* …, */ numN)
console.log(String.fromCodePoint(9731, 9733, 9842, 0x2f804))
// output: "☃★♲你"

9. includes() 判断字符串中是否包含某个字符串

  • includes() 方法执行区分大小写的搜索,以确定是否可以在一个字符串中找到另一个字符串,并根据情况返回 true 或 false。
语法:includes(searchString),includes(searchString, position)
const sentence = '中华人民共和国'
console.log(sentence.includes('人民'))
// output: true

10. indexOf() 返回其第一次出现的位置索引

  • indexOf() 方法在字符串中搜索指定子字符串,并返回其第一次出现的位置索引。

  • 它可以接受一个可选的参数指定搜索的起始位置,如果找到了指定的子字符串,则返回的位置索引大于或等于指定的数字。

  • lastIndexOf() 方法搜索该字符串并返回指定子字符串最后一次出现的索引。

  • 它可以接受一个可选的起始位置参数,并返回指定子字符串在小于或等于指定数字的索引中的最后一次出现的位置。

语法:indexOf(searchString),indexOf(searchString, position)
const paragraph = '千里冰封万里雪飘'
const indexOfFirst = paragraph.indexOf('冰封')
console.log(indexOfFirst)
// output: 2

11. isWellFormed() ?

  • String 值的 isWellFormed() 方法返回一个表示该字符串是否包含单独代理项的布尔值。
语法:isWellFormed()
const strings = [
// 单独的前导代理
'ab\uD800',
'ab\uD800c',
// 单独的后尾代理
'\uDFFFab',
'c\uDFFFab',
// 格式正确
'abc',
'ab\uD83D\uDE04c',
]
for (const str of strings) {
console.log(str.isWellFormed())
}
// 输出:
// false
// false
// false
// false
// true
// true

12. localeCompare() ?

  • localeCompare() 方法返回一个数字,表示参考字符串在排序顺序中是在给定字符串之前、之后还是与之相同。
  • 在支持 Intl.Collator API 的实现中,该方法仅是调用了 Intl.Collator 方法。
语法:localeCompare(compareString, locales, options)
const a = 'réservé' // 带重音符号,小写
const b = 'RESERVE' // 无重音符号,大写
console.log(a.localeCompare(b))
// output: 1
console.log(a.localeCompare(b, 'en', { sensitivity: 'base' }))
// output: 0

13. match() 检索字符串与正则表达式匹配结果

  • match() 方法检索字符串与正则表达式进行匹配的结果。
语法:match(regexp)
const paragraph = 'The PWS quick brown fox jumps over the lazy dog. It barked.'
const regex = /[A-Z]/g
const found = paragraph.match(regex)
console.log(found)
// output: Array ["T", "P", "W", "S", "I"]

14. matchAll()

  • matchAll() 方法返回一个迭代器,该迭代器包含了检索字符串与正则表达式进行匹配的所有结果(包括捕获组)。
语法:matchAll(regexp)
const regexp = /t(e)(st(\d?))/g
const str = 'test1test2'
const array = [...str.matchAll(regexp)]
console.log(array)
// output: Array [Array ["test1", "e", "st1", "1"], Array ["test2", "e", "st2", "2"]]
console.log(array[0])
// output: Array ["test1", "e", "st1", "1"]
console.log(array[1])
// output: Array ["test2", "e", "st2", "2"]

15. normalize() Unicode 标准化输出

  • String 的 normalize() 方法返回该字符串的 Unicode 标准化形式。
语法:normalize(form)
const name1 = '\u0041\u006d\u00e9\u006c\u0069\u0065'
const name2 = '\u0041\u006d\u0065\u0301\u006c\u0069\u0065'

console.log(`${name1}, ${name2}`)
// output: "Amélie, Amélie"
console.log(name1 === name2)
// output: false
console.log(name1.length === name2.length)
// output: false

const name1NFC = name1.normalize('NFC')
const name2NFC = name2.normalize('NFC')

console.log(`${name1NFC}, ${name2NFC}`)
// output: "Amélie, Amélie"
console.log(name1NFC === name2NFC)
// output: true
console.log(name1NFC.length === name2NFC.length)
// output: true

16. padEnd() 按固定长度填充字符串 至尾部

  • padEnd() 方法会将当前字符串从末尾开始填充给定的字符串(如果需要会重复填充),直到达到给定的长度。
  • 填充是从当前字符串的末尾开始的。
语法:padEnd(targetLength, padString)
const str1 = 'Breaded Mushrooms'
console.log(str1.padEnd(25, 'A'))
// output: "Breaded MushroomsAAAAAAAA"
const str2 = '200'
console.log(str2.padEnd(5))
// output: "200 "

17. padStart() 按固定长度填充字符串 至首部

  • padStart() 方法用另一个字符串填充当前字符串(如果需要会重复填充),直到达到给定的长度。填充是从当前字符串的开头开始的。
语法:padStart(targetLength, padString)
const str1 = '5'
console.log(str1.padStart(10, '0'))
// output: "0000000005"

18. String.raw()

  • String.raw() 静态方法是模板字符串的标签函数。它的作用类似于 Python 中的 r 前缀或 C# 中用于字符串字面量的 @ 前缀。它用于获取模板字符串的原始字符串形式——即,替换表达式
  • (例如 ${foo})会被替换处理,但转义序列(例如 \n)不会被处理。
语法:String.raw(strings, ...substitutions)
// String.raw`templateString`
// 创建使用Windows的变量
// 不转义反斜杠的路径:
const filePath = String.raw`C:\Development\profile\aboutme.html`
console.log(`The file was uploaded from: ${filePath}`)
// output: "The file was uploaded from: C:\Development\profile\aboutme.html"

19. repeat() 重复几次字符串副本

  • repeat() 方法构造并返回一个新字符串,其中包含指定数量的所调用的字符串副本,这些副本连接在一起。
语法:
const mood = 'Happy! '
console.log(`I feel ${mood.repeat(3)}`)
// output: "I feel Happy! Happy! Happy! "

20. replace() 更换,replaceAll() 更换全部

  • replace() 更换一个
  • replace() 方法返回一个新字符串,其中一个、多个或所有匹配的 pattern 被替换为 replacement。
  • pattern 可以是字符串或 RegExp,replacement 可以是字符串或一个在每次匹配时调用的函数。
  • 如果 pattern 是字符串,则只会替换第一个匹配项。
  • 原始的字符串不会改变。
  • replaceAll() 更换全部
  • replaceAll() 方法返回一个新字符串,其中所有匹配 pattern 的部分都被替换为 replacement。
  • pattern 可以是一个字符串或一个 RegExp,replacement 可以是一个字符串或一个在每次匹配时调用的函数。
  • 原始字符串保持不变。
语法:replace(pattern, replacement)
const p = '千里冰封,万里雪飘'
console.log(p.replace('万里', 'monkey'))
// output:"千里冰封,monkey雪飘"
const regex = /万里/i
console.log(p.replace(regex, 'ferret'))
// output: "千里冰封,ferret雪飘"

21. search() 根据正则表达式搜索

  • search() 方法用于在 String 对象中执行正则表达式的搜索,寻找匹配项。
  • 好像不是我想的那样
语法:search(regexp)
const paragraph =
'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?'
// Any character that is not a word character or whitespace
const regex = /[^\w\s]/g
console.log(paragraph.search(regex))
// Expected output: 43
console.log(paragraph[paragraph.search(regex)])
// Expected output: "."

22. slice() 片 截取字符串中的一部分内容

  • slice() 方法提取字符串的一部分,并将其作为新字符串返回,而不修改原始字符串。
语法:slice(indexStart, indexEnd)
const str = '千里冰封,万里雪飘'
console.log(str.slice(2))
// output: "冰封,万里雪飘"
console.log(str.slice(4, 7))
// output: ",万里"
console.log(str.slice(-2))
// output: "雪飘"
console.log(str.slice(-9, -5))
// output: "千里冰封"

23. split() 字符串转数组

  • split() 方法接受一个模式,通过搜索模式将字符串分割成一个有序的子串列表,将这些子串放入一个数组,并返回该数组。
语法:split(separator),split(separator, limit)
const str = '千里冰封,万里雪飘.'

const words = str.split(',')
console.log(words)
// output: Array ["千里冰封", "万里雪飘."]
const chars = str.split('')
console.log(chars)
// output: Array ["千", "里", "冰", "封", ",", "万", "里", "雪", "飘", "."]
const strCopy = str.split()
console.log(strCopy)
// output: Array ["千里冰封,万里雪飘."]

24. startsWith() 判断某个字符串是否在这个字符串的开头,或某个具体位置

  • String 的 startsWith() 方法用来判断当前字符串是否以另外一个给定的子字符串开头,并根据判断结果返回 true 或 false。
  • starts With 翻译 “开始 在”
语法:startsWith(searchString),startsWith(searchString, position)
const str1 = 'Saturday night plans'
console.log(str1.startsWith('Sat'))
// output: true
console.log(str1.startsWith('Sat', 3))
// output: false

25. substring() 根据索引截切字符串

  • String 的 substring() 方法返回该字符串从起始索引到结束索引(不包括)的部分,如果未提供结束索引,则返回到字符串末尾的部分。
语法:substring(indexStart, indexEnd)
const str = 'Mozilla'
console.log(str.substring(1, 3))
// Expected output: "oz"
console.log(str.substring(2))
// Expected output: "zilla"

26. toLocaleLowerCase() 字符串转小写+区域语言

  • toLocaleLowerCase() 字符串转小写,方法会根据特定区域设置的大小写映射规则,将字符串转换为小写形式并返回。
  • toLocaleUpperCase() 字符串转大写
语法:toLocaleLowerCase(),toLocaleLowerCase(locales)
const dotted = 'İstanbul'
console.log(`EN-US: ${dotted.toLocaleLowerCase('en-US')}`)
// output: "i̇stanbul"
console.log(`TR: ${dotted.toLocaleLowerCase('tr')}`)
// output: "istanbul"

27. toLowerCase() 字符串转小写

  • toLowerCase() 字符串转小写,方法将该字符串转换为小写形式。
  • toUpperCase() 字符串转大写
语法:
const sentence = 'The quick brown fox jumps over the lazy dog.'
console.log(sentence.toLowerCase())
// output: "the quick brown fox jumps over the lazy dog."
console.log(sentence.toUpperCase())
// output: "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."

25. trim() 去除字符串前后空格

  • trim() 方法会从字符串的两端移除空白字符,并返回一个新的字符串,而不会修改原始字符串。
  • 要返回一个仅从一端修剪空白字符的新字符串,请使用 trimStart() 或 trimEnd()。
  • trimStart() 只去除开始部分
  • trimEnd() 只去除尾部部分
语法:trim()
const greeting = '   Hello world!   '
console.log(greeting)
// output: " Hello world! ";
console.log(greeting.trim())
// output: "Hello world!";

26. valueOf()

  • valueOf() 方法返回 String 对象的字符串值。
语法:valueOf()
const stringObj = new String('foo')
console.log(stringObj)
// output: String { "foo" }
console.log(stringObj.valueOf())
// output: "foo"