JavaScript add strings

JavaScript 添加字符串教程展示了如何在 JavaScript 中连接字符串。

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

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

  • +运算符
  • concat方法
  • join方法
  • 格式化字符串

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

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

let a = 'old';
let b = ' tree';

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

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

$ node add_string.js
old tree

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

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 方法通过连接数组的所有元素来创建并返回一个新字符串。

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方法的效率不如+运算符,所以建议改用后者。

let a = 'old';

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

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

JavaScript 添加带有字符串格式的字符串

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

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

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

列出所有 JavaScript 教程。

赞(0) 打赏

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏