JS中一些实用优雅的字符串方法

String.prototype.at()

更优雅的替代 word[word.length -1] ,还可以避免奇葩的Unicode字符出错:

const word = 'JavaScript'
console.log(word.at(0))  // "J"
console.log(word.at(-1))  // "t"

String.prototype.replaceAll()

替换掉所有匹配的字符串,比正则匹配更简单:

const text = 'We are children of darkness, and to darkness we go.'
text.replaceAll('darkness', 'light')
console.log(text)  // 'We are children of light, and to light we go.'

String.prototype.matchAll()

匹配全部:

const log = 'User: 42 Action:login User:99 Action:logout'
const regex = /User:(\d+)/g
console.log([...log.matchAll(regex)])  // [ ["User:42", "42"], ["User:99", "99"]]

padStart() / padEnd()

优雅的字符串补位方法:

const id = '153'
id.padStart(6, '0')  // "000153"
id.padEnd(5, '0')  // "15300"

String.prototype.normalize()

normalize() 方法用于将字符串转换为统一的 Unicode 标准化形式,解决“同一个字符在不同编码表示下看起来一样但实际不同”的问题。

// 字符 "é" 有两种表示方式:
const str1 = "é";           // 单个字符 U+00E9
const str2 = "e\u0301";     // 字母 e (U+0065) + 重音符号 (U+0301)

console.log(str1 === str2); // false!看起来一样,但实际不相等
console.log(str1.length);   // 1
console.log(str2.length);   // 2

console.log(str1.normalize() === str2.normalize()) // true

trimStart() / trimEnd()

很多时候,你其实并不需要用 trim() 这种简单粗暴把两头的空格全砍掉,有时候需要精准打击:

const input = '    hello word     '
console.log(input.trimStart())  // "hello word     "
console.log(input.trimEnd())  // "    hello word"

带有 limit 参数的 split()

split可以加上limit参数,仅保留切割后的前面某几个:

const str = '2026-04-01-Good-Friday is in 2-days, and Easter is in 4-days.'
console.log(str.split('-', 3))  // ['2026', '04', '01']
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容