广州蓝景分享——前端学习5 种在 JavaScript 中获取字符串第一个字符的方法

在这里插入图片描述
在本文中,我们将研究多种方法来轻松获取 JavaScript 中字符串的第一个字符。

1.charAt() 方法

要获取字符串的第一个字符,我们可以在字符串上调用 charAt() ,将 0 作为参数传递。例如,str.charAt(0) 返回 str 的第一个字符。

const str = 'Coding Beauty';
const firstChar = str.charAt(0);
console.log(firstChar); // C

StringcharAt()返回指定索引处字符串的字符,第一个字符的索引为 0。

2.括号表示法([])属性访问

要获取字符串的第一个字符,我们也可以使用括号表示法 ([]) 访问字符串的 0 属性:

const str = 'Coding Beauty';
const firstChar = str['0'];
console.log(firstChar); // C

当属性名称是无效的 JavaScript 标识符时,括号表示法属性访问是点表示法的有用替代方法。例如,尝试使用点表示法访问 0 属性将导致语法错误,因为 0 不是有效标识符:

const str = 'Coding Beauty';
// SyntaxError: Unexpected number
const firstChar = str.0;
console.log(firstChar);

笔记1

由于 0 是一个整数,我们不需要用引号将它括起来来访问它:

const str = 'Coding Beauty';
// Quotes are not needed to pass 0
const firstChar = str[0];
console.log(firstChar); // C

笔记2

访问不存在的属性在 JavaScript 中返回 undefined。这与返回空字符串 (‘’) 的 charAt() 不同:

const str = 'Coding Beauty';
const char1 = str[20];
const char2 = str.charAt(20);
console.log(char1); // undefined
console.log(char2); // '' (empty string)

3.substring()方法

使用此方法,我们在字符串上调用 substring(),将 0 作为第一个参数传递,将 1 作为第二个参数传递。

const str = 'Coding Beauty';
const firstChar = str.substring(0, 1);
console.log(firstChar); // C

substring() 方法返回开始索引和结束索引之间的字符串部分,这两个索引分别由第一个和第二个参数指定。索引 0 和 1 之间的子字符串是仅包含第一个字符串字符的子字符串。

  1. slice() 方法

使用此方法,我们在字符串上调用 slice(),将 0 作为第一个参数传递,将 1 作为第二个参数传递。

const str = 'Coding Beauty';
const firstChar = str.slice(0, 1);
console.log(firstChar); // C

slice() 方法提取开始和结束索引之间的一部分字符串,这两个索引分别由第一个和第二个参数指定。索引 0 和 1 之间的子字符串是仅包含第一个字符串字符的子字符串。

笔记

slice() 和 substring() 方法在我们的用例中的工作方式类似,但并非总是如此。它们之间的一个区别是,如果第一个大于第二个,则 substring() 交换其参数,而 slice() 返回一个空字符串:

const str = 'Coding Beauty';
const subStr1 = str.substring(6, 0);
const subStr2 = str.slice(6, 0);
// Equivalent to str.substring(0, 6)
console.log(subStr1); // Coding
console.log(subStr2); // '' (empty string)

5.at()方法

获取字符串第一个字符的另一种方法是使用 String at() 方法。我们在字符串上调用 at(),将 0 作为参数传递。

const str = 'Coding Beauty';
const firstChar = str.at(0);
console.log(firstChar); // C

at() 方法返回指定索引处字符串的字符。

笔记

当负整数传递给 at() 时,它从最后一个字符串字符开始倒数。这与返回空字符串的 charAt() 不同:

const str = 'Coding Beauty';
const char1 = str.at(-3);
const char2 = str.charAt(-3);
console.log(char1); // u
console.log(char2); // '' (empty string)

最后

这5种方式虽然都可以实现从JavaScript中获取字符串中第一个字符串的方法,但是具体使用那种情况,我们还是需要根据具体开发项目来,选择最适合最优的方案。

猜你喜欢

转载自blog.csdn.net/qq_43230405/article/details/128239173