JavaScript 中合并字符串的 4 种方法
性能测试
timeInLoop 函数的源代码
以下是 JavaScript 中合并字符串的 4 种方法。我最喜欢使用模板字符串。为什么呢?因为它更易读,无需反斜杠转义引号,没有碍眼的空格分隔符,也不再需要繁琐的加号运算符👏
const icon = '👋';
// Template Strings
`hi ${icon}`;
// join() Method
['hi', icon].join(' ');
// Concat() Method
''.concat('hi ', icon);
// + Operator
'hi ' + icon;
// RESULT
// hi 👋
1. 模板字符串
如果你之前用过其他语言,比如 Ruby,那你一定对字符串插值这个术语很熟悉。模板字符串正是要实现这一点。它提供了一种简单的方法,让你在创建字符串时能够轻松地插入表达式,从而保持代码的可读性和简洁性。
const name = 'samantha';
const country = '🇨🇦';
字符串连接中缺少空格的问题
在模板字符串出现之前,我的字符串会是这样的结果😫
"Hi, I'm " + name + "and I'm from " + country;
☝️ 你发现我的错误了吗?我漏了一个空格😫。这是字符串连接时非常常见的问题。
// Hi, I'm samanthaand I'm from 🇨🇦
已使用模板字符串解决
使用模板字符串,这个问题就解决了。你可以精确地编写字符串的显示方式。因此,很容易就能发现是否缺少空格。现在可读性超棒,太好了!👏
`Hi, I'm ${name} and I'm from ${country}`;
2. join()
该join方法将数组中的元素组合起来并返回一个字符串。由于它处理的是数组,因此如果您需要添加其他字符串,它会非常方便。
const array = ['My handles are'];
const handles = [instagram, twitter, tiktok].join(', '); // @samanthaming, @samantha_ming, @samanthaming
array.push(handles); // ['My handles are', '@samanthaming, @samantha_ming, @samanthaming']
array.join(' ');
// My handles are @samanthaming, @samantha_ming, @samanthaming
自定义分隔符
它的优点在于join你可以自定义数组元素的组合方式。你可以通过在其参数中传递分隔符来实现这一点。
const array = ['My handles are '];
const handles = [instagram, twitter, tiktok].join(', '); // @samanthaming, @samantha_ming, @samanthaming
array.push(handles);
array.join('');
// My handles are @samanthaming, @samantha_ming, @samanthaming
3. concat()
通过concat使用该方法,您可以创建一个新字符串。
const instagram = '@samanthaming';
const twitter = '@samantha_ming';
const tiktok = '@samanthaming';
'My handles are '.concat(instagram, ', ', twitter', ', tiktok);
// My handles are @samanthaming, @samantha_ming, @samanthaming
将字符串与数组结合使用
您还可以使用concat它来组合字符串和数组。当我传递一个数组参数时,它会自动将数组元素转换为以逗号分隔的字符串,。
const array = [instagram, twitter, tiktok];
'My handles are '.concat(array);
// My handles are @samanthaming,@samantha_ming,@samanthaming
如果您希望格式更好,我们可以使用join自定义分隔符。
const array = [instagram, twitter, tiktok].join(', ');
'My handles are '.concat(array);
// My handles are @samanthaming, @samantha_ming, @samanthaming
4. 加号运算符 (+)
使用运算符合并字符串时,有一点很有意思+。你可以用它来创建一个新字符串,也可以通过在现有字符串后添加新内容来修改它。
非突变
这里我们用它+来创建一个全新的字符串。
const instagram = '@samanthaming';
const twitter = '@samantha_ming';
const tiktok = '@samanthaming';
const newString = 'My handles are ' + instagram + twitter + tiktok;
突变
我们还可以使用 `.` 将其附加到现有字符串中+=。因此,如果出于某种原因,您需要一种修改现有字符串的方法,这可能是一个可行的选择。
let string = 'My handles are ';
string += instagram + twitter;
// My handles are @samanthaming@samantha_ming
哎呀😱 又忘了加空格了。看!连接字符串的时候真的很容易漏掉空格。
string += instagram + ', ' + twitter + ', ' + tiktok;
// My handles are @samanthaming, @samantha_ming, @samanthaming
感觉还是太乱了,我们还是把它加join进去吧!
string += [instagram, twitter, tiktok].join(', ');
// My handles are @samanthaming, @samantha_ming, @samanthaming
字符串中的转义字符
当字符串中包含特殊字符时,在合并字符串之前需要先对这些字符进行转义。让我们来看几个例子,看看如何进行转义 💪
转义单引号或撇号 (')
创建字符串时,可以使用单引号或双引号。了解这一点后,如果字符串中包含单引号,一个非常简单的解决方法是使用相反的双引号来创建字符串。
const happy = 🙂;
["I'm ", happy].join(' ');
''.concat("I'm ", happy);
"I'm " + happy;
// RESULT
// I'm 🙂
当然,你也可以使用反斜杠 (\ \) 来转义字符。但我发现这样写有点难读,所以我不常用这种方法。
const happy = 🙂;
['I\'m ', happy].join(' ');
''.concat('I\'m ', happy);
'I\'m ' + happy;
// RESULT
// I'm 🙂
因为模板字符串使用的是反引号,所以这种情况不适用于它👍
转义双引号 ("")
与转义单引号类似,我们可以使用相反的方法来转义双引号。因此,要转义双引号,我们将使用单引号。
const flag = '🇨🇦';
['Canada "', flag, '"'].join(' ');
''.concat('Canada "', flag, '"');
'Canada "' + flag + '"';
// RESULT
// Canada "🇨🇦"
是的,也可以使用反斜杠转义字符。
const flag = '🇨🇦';
['Canada "', flag, '"'].join(' ');
''.concat('Canada "', flag, '"');
'Canada "' + flag + '"';
// RESULT
// Canada "🇨🇦"
因为模板字符串使用的是反引号,所以这种情况不适用于它👍
转义反引号
因为模板字符串使用反引号来创建字符串,所以当想要输出该字符时,必须使用反斜杠对其进行转义。
const flag = '🇨🇦';
`Use backtick \`\` to create a template string`;
// RESULT
// Use backtick `` to create a template string
因为其他字符串创建操作未使用反引号,所以这种情况不适用于它们👍
应该如何使用?
我展示了一些连接字符串的不同方法。哪种方法更好取决于具体情况。就风格偏好而言,我喜欢遵循 Airbnb 的风格指南。
在以编程方式构建字符串时,请使用模板字符串而不是字符串拼接。eslint: prefer-template template-curly-spacing
所以,模板字符串万岁!👑
为什么其他方法仍然重要?
了解其他方法仍然很重要。为什么呢?因为并非所有代码库都遵循这条规则,或者你可能正在处理一个遗留代码库。作为开发人员,我们需要能够适应并理解我们所处的任何环境。我们的职责是解决问题,而不是抱怨技术有多老旧(笑)😂 除非这种抱怨能伴随着切实可行的改进措施。那样的话,我们就取得了进步👏
浏览器支持
| 浏览器 | 模板字符串 | 加入 | 连接 | + |
|---|---|---|---|---|
| Internet Explorer | ❌ | ✅ IE 5.5 | ✅ IE 4 | ✅ IE 3 |
| 边缘 | ✅ | ✅ | ✅ | ✅ |
| 铬合金 | ✅ | ✅ | ✅ | ✅ |
| 火狐浏览器 | ✅ | ✅ | ✅ | ✅ |
| 狩猎之旅 | ✅ | ✅ | ✅ | ✅ |
资源
- MDN 模板字面量
- MDN:连接
- MDN:加入
- MDN:+
- Stack Overflow:在 JavaScript 中连接字符串最有效的方法是什么?
- 连接字符串的三种方法
- Digital Ocean:如何在 JavaScript 中处理字符串
- 爱彼迎风格指南
- ESLint:首选模板
- SamanthaMing:如何使用模板字面量创建多行字符串
- SamanthaMing:加入
感谢阅读❤
想了解更多代码技巧,请访问samanthaming.com
| 🌟推特 | 👩🏻💻 SamanthaMing.com |
