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:Let str=’This is osman’;console.log(str.replace(‘osman’,’kader’));Result: This is kader
3、indexOf()
此方法返回數字值。它是找出任何字符串的索引號。
Syntax: concat(str1, str2)Example:const paragraph =’JavaScript is the world's most popular programming language.’;const indexOfFirst = paragraph.indexOf(‘language'’);console.log(indexOfFirst);Result:50
4、concat()
Syntax: concat(str1, str2)Example:let str1=’My name is ‘;let str2=’Mohammad Osman Goni’;console.log(concat(str1,str2);Result: “My name is Mohamad Osman Goni”
5、repeat()
此方法返回一個新字符串,其中包含給定字符串的指定副本數。
Syntax: repeat(count);Example:Let str=’Bangladesh’console.log(str.repeat(3));Result: ` Bangladesh Bangladesh Bangladesh `
6、split()
此方法用分隔符分割字符串并返回一個數組。當字符串為空時,split() 方法返回一個包含一個空字符串的數組。
Syntax: split(separator)Example:let str=’ JavaScript is 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 = new String('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() 方法用于將任何字符串轉換為小寫并返回一個新字符串。
Syntax: toLowerCase();Example: let str=’BEYOND WEBSITES AND APPS, DEVELOPERS CAN ALSO USE JAVASCRIPT TO BUILD SIMPLE WEB SERVERS AND DEVELOP THE BACK-END INFRASTRUCTURE USING NODE.JS.’console.log(str.toLowerCase())Result: "beyond websites and apps, developers can also use javascript to build simple web servers and develop the back-end infrastructure using node.js."
感謝你的閱讀。
學習更多技能
請點擊下方公眾號
![]()

評論
圖片
表情
