《掌握 JavaScript 字符串操作,这一篇就够了!》

你还在为 JavaScript 的字符串操作犯愁吗?

  • 如何高效查找、替换、拆分字符串?
  • match() 和 matchAll() 到底有什么区别?
  • 什么时候用 replace(),什么时候用 replaceAll()?
  • 正则表达式搭配字符串方法,能玩出什么花样?

📌 别担心!这篇文章帮你全面梳理 JavaScript 字符串方法,助你写出更优雅、更高效的代码!

实例方法

string.at(index)

  • index:查找的索引
  • 支持负索引
  • 超出范围返回空字符串

返回位于索引值的字符。

ini 复制代码
 const sentence = "The quick brown fox jumps over the lazy dog.";
 let index = -4;
 console.log(sentence.at(index)) //d

string.charAt(index)

  • index:查找的索引
  • 不支持负索引
  • 超出范围返回undefined

返回位于索引值的字符。

ini 复制代码
 const sentence = "The quick brown fox jumps over the lazy dog.";
 let index = -4;
 console.log(sentence.at(index)) //负索引被当成0,返回'T'
 index=5;
 console.log(sentence.charAt(index))//u

string.charCodeAt(index)

  • index:查找的索引
  • 不支持负索引

返回位于索引值字符的Unicode 编码。

ini 复制代码
 const sentence = "The quick brown fox jumps over the lazy dog.";
 const index = 4;
 console.log(sentence.charCodeAt(index)) //113

string.codePointAt(index)

  • index:查找的索引
  • 不支持负索引

返回完整的Unicode 代码点(code point),可超过 65535

rust 复制代码
 const str = "A💖"; // "A" 是基本字符, "💖" 是一个 Unicode 补充字符(U+1F496)
 console.log(str.codePointAt(1)); // 128150 (💖 的完整 Unicode 代码点)

string.concat(str1, str2, /* ..., */ strN)

  • str1、......、strN:需要连接的字符串。

将字符串连接起来。

ini 复制代码
 const str1 = "Hello";
 const str2 = "World";
 console.log(str1.concat(" ", str2));
 // Expected output: "Hello World"

string.endsWith(searchString,endPosition)

  • searchString:要搜索的作为结尾得字符串。
  • endPosition?:预期找到searchString的末尾位置,默认味str.length。

判断一个字符串是否以指定字符串结尾,如果是则返回true,否则返回false。

arduino 复制代码
 const str1 = "Cats are the best!";
 console.log(str1.endsWith("best!"));//true

string.startWith(searchString, position)

  • searchString:要搜索的作为结尾得字符串。
  • endPosition?:预期找到searchString的末尾位置,默认味str.length。

判断一个字符串是否以指定字符串开头,如果是则返回true,否则返回false。

arduino 复制代码
 const str1 = "Cats are the best!";
 console.log(str1.endsWith("Cats"));//true

string.includes(searchString,endPosition)

  • searchString:要搜索的字符串。
  • position?:在字符串中开始搜索的位置。
ini 复制代码
 const sentence = "The quick brown fox jumps over the lazy dog.";
 const word = "fox";
 console.log(sentence.includes(word));//true

string.indexOf(searchValue)

  • searchValue:要搜索的子字符串。
  • position?:从position开始搜索。

搜索指定子字符串,并返回其第一次出现的位置索引。如果没有则返回-1。

ini 复制代码
 const paragraph = "I think Ruth's dog is cuter than your dog!";
 const searchTerm = "dog";
 consolee.log(paragraph.indexOf(searchTerm))//15

string.lastIndexOf(searchString, position)

  • searchValue:要搜索的子字符串。
  • position?:搜索到position为止。

搜索字符串并返回指定子字符串最后一次出现的索引。

ini 复制代码
 const paragraph = "I think Ruth's dog is cuter than your dog!";
 const searchTerm = "dog";
 console.log(paragraph.lastIndexOf(searchTerm));//38

string.match(regexp)

  • regexp:一个正则表达式对象。

检索字符串与正则表达式进行匹配的结果,返回数组,只包含匹配到的字符串。

ini 复制代码
 const paragraph = "The quick brown fox jumps over the lazy dog. It barked.";
 const regex = /[A-Z]/g;
 console.log(paragraph.match(regex));// Array ["T", "I"]

string.matchAll(regexp)

  • regexp:一个正则表达式对象。
  • 正则表达式必须带有全局修饰符。

返回一个迭代器,该迭代器包含了检索字符串与正则表达式进行匹配的所有结果(包括捕获组)。

ini 复制代码
 const regexp = /t(e)(st(\d?))/g;
 const str = "test1test2";
 const array = [...str.matchAll(regexp)];
 console.log(array[0]);//["test1", "e", "st1", "1"]

string.padEnd(targetLength, padString)

  • targetLength:当前str填充后的长度。
  • padString?:用于填充当前 str 的字符串,默认填充空字符。

将当前字符串从末尾开始填充给定的字符串(如果需要会重复填充),直到达到给定的长度。填充是从当前字符串的末尾开始的。

ini 复制代码
 const str1 = "Breaded Mushrooms";
 console.log(str1.padEnd(25, "."));//Breaded Mushrooms........
 const str2 = "200";
 console.log(str2.padEnd(5));//"200  "

string.padStart(targetLength, padString)

  • targetLength:当前str填充后的长度。
  • padString?:用于填充当前 str 的字符串,默认填充空字符。

另一个字符串填充当前字符串(如果需要会重复填充),直到达到给定的长度。填充是从当前字符串的开头开始的。

arduino 复制代码
 const str1 = "5";
 console.log(str1.padStart(2, "0"));// "05"

string.repeate(count)

  • count:重复次数

造并返回一个新字符串,其中包含指定数量的所调用的字符串副本,这些副本连接在一起。

ini 复制代码
 const mood = "Happy! ";
 console.log(mood.repeat(3));//Happy! Happy! Happy! 

string.replace(pattern, replacement)

  • pattern:字符串或者正则表达式。
  • replacement:替换后的字符串

replace() 方法返回一个新字符串,只替换第一个匹配项或使用正则修饰符。

arduino 复制代码
 const paragraph = "I think Ruth's dog is cuter than your dog!";
 console.log(paragraph.replace("Ruth's", "my"));//"I think my dog is cuter than your dog!"

string.replaceAll(pattern, replacement)

  • pattern:字符串或者正则表达式。
  • replacement:替换后的字符串。
  • 正则表达式必须携带全部修饰符。

replace() 方法返回一个新字符串, 替换所有匹配项。

arduino 复制代码
 const paragraph = "I think Ruth's dog is cuter than your dog!";
 console.log(paragraph.replace("Ruth's", "my"));//"I think my dog is cuter than your dog!"

string.search(regexp)

  • regexp:正则表达式

在 String 对象中执行正则表达式的搜索,寻找匹配项。

javascript 复制代码
 const paragraph = "I think Ruth's dog is cuter than your dog!";
 const regex = /[^\w\s']/g;
 console.log(paragraph.search(regex));// 41

string.slice(indexStart, indexEnd)

  • indexStart:要返回的子字符串中包含的第一个字符的索引。
  • indexEnd?:要返回的子字符串中排除的第一个字符的索引。

提取字符串的一部分,并将其作为新字符串返回,而不修改原始字符串。

ini 复制代码
 const str = "The quick brown fox jumps over the lazy dog.";
 console.log(str.slice(31));//"the lazy dog."

string.split(separator, limit)

  • separator:分隔符。
  • limit?:在达到limit次分割时停止分割。

通过搜索模式将字符串分割成一个有序的子串列表,将这些子串放入一个数组,并返回该数组。

ini 复制代码
 const str = "The quick brown fox jumps over the lazy dog.";
 const words = str.split(" ");
 console.log(words[3]);// "fox"

string.substring(indexStart,indexEnd)

  • indexStart:返回子字符串中第一个要包含的字符的索引。
  • indexEnd?:返回子字符串中第一个要排除的字符的索引。

返回该字符串从起始索引到结束索引(不包括)的部分,如果未提供结束索引,则返回到字符串末尾的部分。

vbscript 复制代码
 const str = "Mozilla";
 console.log(str.substring(1, 3));//"oz"
 console.log(str.substring(2));//"zilla"

string.trim()

trim() 方法会从字符串的两端移除空白字符,并返回一个新的字符串,而不会修改原始字符串。使用 trimStart()或 trimEnd()可以仅从一端修剪空白字符的新字符串。

vbscript 复制代码
 const greeting = "   Hello world!   ";
 console.log(greeting);//"   Hello world!   ";
 console.log(greeting.trim());//"Hello world!";

✨ 恭喜你!现在你已经掌握了 JavaScript 字符串操作的精髓!

💡 最后一个问题:学会了这些,你准备在项目里怎么用?

🚀 欢迎留言交流你的心得,也可以收藏这篇文章,随时查阅哦!

👉 记住,代码的世界没有尽头,继续探索吧! 🎯

相关推荐
To_OC9 小时前
从一头雾水到跑通全流程:我用一个周末啃透了JWT登录鉴权
前端·后端·http
excel11 小时前
研究 Vue 3 源码的收获
前端·vue.js
可乐鸡翅yeah_13 小时前
业务中 M3U8 水印相关坑,硬水印和动态水印区别
前端·网络·数据库·ffmpeg·m3u8在线
lerhxx13 小时前
AI 应用如何高效优雅地恢复中断?—— "连接解耦 + 状态持久化"
前端·javascript
计算机魔术师13 小时前
METR 演示 AI 智能体如何篡改 Inspect 评估记录以掩盖不当行为
前端
前端snow14 小时前
ai agent --- 异步处理之 Rabbit MQ
前端
念何架构之路14 小时前
zap扩展生态与总结
java·前端·数据库
独孤九剑打醒他14 小时前
【原创开源】【概念设计】源 - 栅 - 漏 - 栅 - 源 横向双栅 MOS,低压交流多值逻辑芯片探索
前端·其他·架构·开源·硬件工程
mantou13215 小时前
我给 AI Agent 做了个「油猴」:让 Claude Code / Codex 直接用你已登录的浏览器
前端·javascript·后端
默_笙15 小时前
🍕 一个主编、三个工种、两本手册:搭一支 AI 调研队
前端·javascript