12

10个很棒的 JavaScript 字符串技巧

 3 years ago
source link: https://blog.csdn.net/qq449245884/article/details/112167561
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

作者:Kai
译者:前端小智
来源:dev

点赞再看,微信搜索**【大迁世界】关注这个没有大厂背景,但有着一股向上积极心态人。本文 GitHub https://github.com/qq449245884/xiaozhi 上已经收录,文章的已分类,也整理了很多我的文档,和教程资料。

最近开源了一个 Vue 组件,还不够完善,欢迎大家来一起完善它,也希望大家能给个 star 支持一下,谢谢各位了。

github 地址:https://github.com/qq449245884/vue-okr-tree

我们称一个字符序列为字符串。这几乎是所有编程语言中都有的基本类型之一。这里跟大家展示关于 JS 字符串的10个很棒的技巧,你可能还不知道哦?

1.如何多次复制一个字符串

JS 字符串允许简单的重复,与纯手工复制字符串不同,我们可以使用字符串的repeat方法。

const laughing = '小智'.repeat(3)
consol.log(laughing) // "小智小智小智"

const eightBits = '1'.repeat(8)
console.log(eightBits) // "11111111"

2. 如何填充一个字符串到指定的长度

有时,我们希望字符串具有特定长度。 如果字符串太短,则需要填充剩余空间,直到达到指定的长度为止。

过去,主要还是使用库 left-pad。 但是,今天我们可以使用padStartSpadEnd方法,选择哪种方法取决于是在字符串的开头还是结尾填充字符串。

// 在开头添加 "0",直到字符串的长度为 8。
const eightBits = '001'.padStart(8, '0')
console.log(eightBits) // "00000001"

//在末尾添加“ *”,直到字符串的长度为5。
const anonymizedCode = "34".padEnd(5, "*")
console.log(anonymizedCode) // "34***"

3.如何将字符串拆分为字符数组

有多种方法可以将字符串分割成字符数组,我更喜欢使用扩展操作符(...):

const word = 'apple'
const characters = [...word]
console.log(characters) // ["a", "p", "p", "l", "e"]

注意,这并不总是像预期的那样工作。有关更多信息,请参见下一个技巧。

4.如何计算字符串中的字符

可以使用length属性。

const word = "apple";
console.log(word.length) // 5

但对于中文来说,这个方法就不太靠谱。

const word = "𩸽"
console.log(word.length) // 2

日本汉字𩸽返回length2,为什么? JS 将大多数字符表示为16位代码点。 但是,某些字符表示为两个(或更多)16 位代码点,称为代理对。 如果使用的是length属性,JS 告诉你使用了多少代码点。 因此,𩸽(hokke)由两个代码点组成,返回错误的值。

那怎么去判断呢,使用解构操作符号(...)

const word = "𩸽"
const characters = [...word]
console.log(characters.length) // 1

这种方法在大多数情况下都有效,但是有一些极端情况。 例如,如果使用表情符号,则有时此长度也是错误的。 如果真想计算字符正确长度,则必须将单词分解为 字素簇(Grapheme Clusters) ,这超出了本文的范围,这里就不在这说明。

5.如何反转字符串中的字符

反转字符串中的字符是很容易的。只需组合扩展操作符(...)、Array.reverse方法和Array.join方法。

const word = "apple"
const reversedWord = [...word].reverse().join("")
console.log(reversedWord) // "elppa"

和前面一样,也有一些边缘情况。遇到边缘的情况就有需要首先将单词拆分为字素簇

6. 如何将字符串中的第一个字母大写

一个非常常见的操作是将字符串的第一个字母大写。虽然许多编程语言都有一种本地方法来实现这一点,但 JS 需要做一些工作。

let word = 'apply'

word = word[0].toUpperCase() + word.substr(1)

console.log(word) // "Apple"

另一种方法:

// This shows an alternative way
let word = "apple";

// 使用扩展运算符(`...`)拆分为字符

const characters = [...word];
characters[0] = characters[0].toUpperCase();
word = characters.join("");

console.log(word); // "Apple"

7.如何在多个分隔符上分割字符串

假设我们要在分隔符上分割字符串,第一想到的就是使用split方法,这点,智米们肯定知道。 但是,有一点大家可能不知道,就是split可以同时拆分多个分隔符, 使用正则表达式就可以实现:

// 用逗号(,)和分号(;)分开。

const list = "apples,bananas;cherries"
const fruits = list.split(/[,;]/)
console.log(fruits); // ["apples", "bananas", "cherries"]

8.如何检查字符串是否包含特定序列

字符串搜索是一项常见的任务。 在 JS 中,你可以使用String.includes方法轻松完成此操作。 不需要正则表达式。

const text = "Hello, world! My name is Kai!"
console.log(text.includes("Kai")); // true

9.如何检查字符串是否以特定序列开头或结尾

在字符串的开头或结尾进行搜索,可以使用String.startsWithString.endsWith方法。

const text = "Hello, world! My name is Kai!"

console.log(text.startsWith("Hello")); // true

console.log(text.endsWith("world")); // false

10.如何替换所有出现的字符串

有多种方法可以替换所有出现的字符串。 可以使用String.replace方法和带有全局标志的正则表达式。 或者,可以使用新的String.replaceAll方法。 请注意,并非在所有浏览器和Node.js 版本中都可用此新方法。

const text = "I like apples. You like apples."

console.log(text.replace(/apples/g, "bananas"));
// "I like bananas. You like bananas."

console.log(text.replaceAll("apples", "bananas"));
// "I lik

字符串是几乎所有编程语言中最基本的数据类型之一。同时,它也是新开发人员学习的最早的数据类型之一。然而,尤其是在JavaScript中,许多开发人员并不知道关于字符串的一些有趣的细节。希望此文对你有所帮助。

我是小智,我们下期见。


代码部署后可能存在的BUG没法实时知道,事后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给大家推荐一个好用的BUG监控工具 Fundebug

原文:https://dev.to/kais_blog/10-awesome-string-tips-you-might-not-know-about-4ep2

文章每周持续更新,可以微信搜索「 大迁世界 」第一时间阅读和催更(比博客早一到两篇哟),本文 GitHub https://github.com/qq449245884/xiaozhi 已经收录,整理了很多我的文档,欢迎Star和完善,大家面试可以参照考点复习,另外关注公众号,后台回复福利,即可看到福利,你懂的。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mQVfvbwJ-1609719158863)(/img/remote/1460000020353567?w=800&h=400)]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK