ZetCode

JavaScript 添加字符串

最后修改于 2023 年 10 月 18 日

在本文中,我们将展示如何在 JavaScript 中连接字符串。

在 JavaScript 中,字符串是一个用于表示和操作字符序列的对象。

在 JavaScript 中,有几种添加字符串的方法。

JavaScript 使用 + 运算符添加字符串

连接字符串最简单的方法是使用 ++= 运算符。 + 运算符既用于添加数字,也用于添加字符串; 在编程中,我们说该运算符是 *重载的*。

add_string.js
let a = 'old';
let b = ' tree';

let c = a + b;
console.log(c);

在示例中,我们使用 + 运算符添加两个字符串。

$ node add_string.js
old tree

在第二个示例中,我们使用了复合加法运算符。

add_string2.js
let msg = 'There are';

msg += ' three falcons';
msg += ' in the sky';

console.log(msg);

该示例使用 += 运算符构建消息。

$ node add_string2.js
There are three falcons in the sky

JavaScript 使用 join 添加字符串

join 方法通过连接数组的所有元素来创建并返回一个新字符串。

joining.js
let words = ['There', 'are', 'three', 'falcons', 'in', 'the', 'sky'];

let msg = words.join(' ');
console.log(msg);

该示例通过连接数组中的单词来形成一条消息。

$ node joining.js 
There are three falcons in the sky

JavaScript 使用 concat 添加字符串

concat 方法将字符串参数连接到调用字符串并返回一个新字符串。

由于 concat 方法不如 + 运算符高效,因此建议使用后者。

concat.js
let a = 'old';

let c = a.concat(' tree');
console.log(c);

该示例使用内置的 concat 方法连接两个字符串。

JavaScript 使用字符串格式化添加字符串

我们可以使用字符串格式化来构建 JavaScript 字符串,这本质上是字符串添加的另一种形式。

formatting.js
let w1 = 'two';
let w2 = 'eagles';

let msg = `There are ${w1} ${w2} in the sky`;
console.log(msg);

该示例使用模板字面量构建一条消息。

$ node formatting.js 
There are two eagles in the sky

来源

JS 字符串文档

在本文中,我们介绍了在 JavaScript 中连接字符串的几种方法。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。 我拥有十多年教授编程的经验。

查看 所有 JavaScript 教程。