10 個重要的 Javascript 字串方法

「來源: |web前端開發 ID:web_qdkf」

10 個重要的 Javascript 字串方法

英文 | https://osmangoni0827。medium。com/charat-aac315ec813e

翻譯 | 楊小二

1、charAt()

這是非常有用的字串方法。此方法返回字元值。它找出指定的索引形式 Any String。此方法以任意數字為引數。第一個字元的索引為 0。如果沒有為 charAt() 提供索引,則預設為 0。

Syntax : charAt(index);Example:let str=`Bangladesh is a popular country`。console。log(`The character at index 2 is ${sentence。charAt(2)} `)output: The character at index 2 is n

2、replace()

replace() 方法返回一個新字串。它是替換字串的一部分。

Syntax: replace(‘substr’,`newsubstr`);Example:Letstr=’This is osman’;console。log(str。replace(‘osman’,’kader’));Result: This is kader

3、indexOf()

此方法返回數字值。它是找出任何字串的索引號。

Syntax: concat(str1, str2)Example:constparagraph =’JavaScript is the world‘s most popular programming language。’;constindexOfFirst = paragraph。indexOf(‘language’’);console。log(indexOfFirst);Result:50

4、concat()

Syntax: concat(str1, str2)Example:letstr1=’My name is ‘;letstr2=’Mohammad Osman Goni’;console。log(concat(str1,str2);Result: “My name is Mohamad Osman Goni”

5、repeat()

此方法返回一個新字串,其中包含給定字串的指定副本數。

Syntax: repeat(count);Example:Letstr=’Bangladesh’console。log(str。repeat(3));Result: ` Bangladesh Bangladesh Bangladesh `

6、split()

此方法用分隔符分割字串並返回一個數組。當字串為空時,split() 方法返回一個包含一個空字串的陣列。

Syntax: split(separator)Example:let str=’ JavaScriptis a text-based programming language used both on the client-side and server-side’;console。log(str。split(‘ ’);Result: Array [“JavaScript”, “is”, “a”, “text-based”, “programming”, “language”, “used”, “both”, “on”, “the”, “client-side”, “and”, “server-side”]

7、trim()

trim() 方法從字串中刪除開頭和結尾的所有空白並返回一個新字串。

Syntax: trim()Example:const greeting = ‘ Hello world! ’;console。log(greeting);Result: `Hello world`

8、toString()

此方法將字串轉換為任何物件。它返回一個表示指定物件的字串。

Syntax: toString();Example:let str = newString(‘Hello world’);console。log(str。toString());Result: `Hello world`;

9、toUpperCase()

此方法用於將字串值轉換為大寫並返回一個新字串。

Syntax: toUpperCase()Example: let str=` JavaScript allows users to interact with web pages`console。log(str。toUpperCase());Result : “JAVASCRIPT ALLOWS USERS TO INTERACT WITH WEB PAGES”

10、toLowerCase()

toLowerCase() 方法用於將任何字串轉換為小寫並返回一個新字串。

10 個重要的 Javascript 字串方法