」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > JavaScript 中的字串方法

JavaScript 中的字串方法

發佈於2024-08-24
瀏覽:573

String methods in javascript

什麼是字串?

*用引號括起來的一個或多個字元的序列稱為字串。
*引號可以是單引號 '' 或雙引號 " " 或反引號 ``.
並且,字元序列可以是字母、數字、符號等

字串方法

1.charAt(索引)

*charAt() 傳回字串中指定索引處的字元。
*字串的第一個字元的索引為 0,第二個字元的索引為 1,依此類推...

例子

let text = "HELLO";
讓 char = text.charAt(0);
console.log(char)// 回傳“H”

2.長度

*此屬性傳回字串中的字元數。

例子

let text = "HELLO";
讓長度=文本.長度;
console.log(length) // 回傳 5

3.切片(開始,結束)

*提取字串的一部分並將其作為新字串傳回。起始索引包含在內,結束索引不包含。

例子

let text = "HELLO WORLD";
讓部分 = text.slice(0, 5);
console.log(part) // 回傳「HELLO」

4.子字串(開始,結束)

*與 slice() 類似,但將負索引視為 0。它會提取兩個指定索引之間的字元。

例子

let text = "HELLO WORLD";
讓部分 = text.substring(0, 5);
console.log(part)// 回傳「HELLO」

5.toUpperCase()

*將字串中的所有字元轉換為大寫。

例子

let text = "你好";
讓 upper = text.toUpperCase();
console.log(upper)// 回傳「HELLO」

6.toLowerCase()

*將字串中的所有字元轉換為小寫。

例子

let text = "HELLO";
讓 lower = text.toLowerCase();
console.log(lower)// 回傳「hello」

7.修剪()

*刪除字串兩端的空格。

例子

let text = "你好";
讓修剪 = text.trim();
console.log(trimmed) // 回傳「hello」

8.concat()

*連接兩個或多個字串並傳回一個新字串。

例子

let text1 = "你好";
讓text2 =“世界”;
讓組合 = text1.concat(" ", text2);
console.log(combined) // 回傳「Hello World」

9.indexOf(子串)

*傳回指定子字串第一次出現的索引。如果沒有找到則回傳-1。

例子

let text = "HELLO WORLD";
讓索引 = text.indexOf("O");
console.log(index)//返回4

10.替換(搜尋值,新值)

*以新值取代第一次出現的指定值。

例子

let text = "HELLO WORLD";
let newText = text.replace("WORLD", "EVERYONE");
console.log(newText)// 回傳「HELLO EVERYONE」

11.replaceAll(搜尋值,新值)

*以新值取代所有出現的指定值。

例子

let text = "HELLO WORLD WORLD";
let newText = text.replaceAll("WORLD", "EVERYONE");
console.log(newText)// 回傳「HELLO EVERYONE EVERYONE」

12.split(分隔符號)

*根據指定的分隔符號將字串拆分為子字串陣列。

例子

let text = "HELLO WORLD";
讓 parts = text.split(" ");
console.log(parts)// 返回 ["HELLO", "WORLD"]

13.連接(分隔符號)

*使用指定的分隔符號將陣列的元素連接到字串中。

例子

let array = ["HELLO", "WORLD"];
let join = array.join(" ");
console.log(joined)// 回傳「HELLO WORLD」

14.startsWith(搜尋字串)

*檢查字串是否以指定字串開頭。

例子

let text = "HELLO WORLD";
讓starts = text.startsWith("HELLO");
console.log(starts)//回傳true

15.endsWith(搜尋字串)

*檢查字串是否以指定字串結尾。

例子

let text = "HELLO WORLD";
讓結束 = text.endsWith("WORLD");
console.log(ends)//回傳true

16.includes(搜尋字串)

*檢查字串是否包含指定的子字串。

例子

let text = "HELLO WORLD";
令includes = text.includes(“LO”);
console.log(includes)//回傳true

版本聲明 本文轉載於:https://dev.to/t_shivakumar_0dc86c6486c/string-methods-in-javascript-516p?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3