[Day26] String methods 字串操作方法(1)

今天来了解字串的操作方法有哪些,至少读过或操作一次,或许未来有哪些情境可以用到。

charAt()

回传指定索引值的字元,预设值为 0,如下例:若没输入值则显示 J。可以搭配 length 使用,输入 1 是倒数第一位的意思,以此类推。

let str1 = "JavaScript";
str1.charAt(3); // a
str1.charAt(0); // J
str1.charAt(str1.length - 1); // t

charCodeAt()

回传指定索引值字元的 Unicode,也可以搭配 length。

let str2 = "ABCDE";
str2.charCodeAt(0); // 65,A
str2.charCodeAt(1); // 66,B
str2.charCodeAt(2); // 67,C
str2.charCodeAt(str2.length - 2); // 68,D

concat()

功能是连接两个或多个字串。

let mrLonely = "We're living in a twilight world,";
let superEdger = " and there are no friends at dusk.";
let sign = mrLonely.concat(superEdger);
console.log(sign); // We're living in a twilight world, and there are no friends at dusk.

endsWith()

检查字串是否以指定值为结束;有两个参数,第一个为指定寻找的值,第二个是 length 可设可不设:

let str1 = "We're living in a twilight world."
str1.endsWith("twilight", 26); // true
str1.endsWith("twilight"); // false

fromCharCode()

可将 Unicode 值转换为字符。

String.fromCharCode(76, 79, 86, 69); // LOVE

includes()

检查字串里是否包含指定的值,有两个参数,第一个是指定值,第二是开始检查的位置(可不填)。

let str3 = "Where is my love?"
str3.includes("love") // true
str3.includes("love", 12) // true
str3.includes("love", 14) // false

indexOf()

寻找指定的字,有区分大小写,符合的话会回报第一个字元的 index 值(如举例中的:7),若不符合则回传 -1

let motoo = "Stay hungry, stay foolish.";
motoo.indexOf("ngry"); // 7
motoo.indexOf("abc"); // -1

lastIndexOf()

与 indexOf()类似寻找指定的字串,可以由字面理解「最後一个」,不同在於他是从句子後面找回来,而回传仍然是 index 值。

let motoo = "Stay hungry, stay foolish.";
motoo.lastIndexOf("tay"); // 14
motoo.lastIndexOf("abc"); // -1

参考资料

W3C-string


<<:  Day#26 传送对话(1)

>>:  Day 26 - styled-components 笔记1

[Day25]程序菜鸟自学C++资料结构演算法 – 快速排序法(Quick Sort)

前言:讲解完了基础的排序法後,接着要来讲解比较高等的排序法,今天和明天要介绍的都是始於分割资料的排序...

进击的软件工程师之路-软件战斗营 第八周

学习进度 资料结构 杂凑(Hashing) 哈希(Hash) HashMap 游戏专题 (自学)碰撞...

Day 24 : Tkinter-利用Python建立GUI(元件篇)

今天会开始来讲元件的部分~ 通用参数 height : 高度 width : 宽度 fg : 文字颜...

DAY27 CNN(卷积神经网路 续一)

昨天介绍完CNN卷积神经网路,今天要来研究CNN卷积神经网路正向传播程序: 首先先决定资料集大小: ...

Day-21 SONY 的刁蛮三公主、PS3 步步艰辛的复兴之路

以 PS1 和 PS2 称霸於前两个世代的 SONY、在新的世代推出的主机当然就叫做 PS3。然而身...