10 個(gè)重要的 Javascript 字符串方法

英文 | https://osmangoni0827.medium.com/charat-aac315ec813e
翻譯 | 楊小二
1、charAt()
這是非常有用的字符串方法。此方法返回字符值。它找出指定的索引形式 Any String。此方法以任意數(shù)字為參數(shù)。第一個(gè)字符的索引為 0。如果沒(méi)有為 charAt() 提供索引,則默認(rèn)為 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() 方法返回一個(gè)新字符串。它是替換字符串的一部分。
Syntax: replace(‘substr’,`newsubstr`);Example:Let str=’This is osman’;console.log(str.replace(‘osman’,’kader’));Result: This is kader
3、indexOf()
此方法返回?cái)?shù)字值。它是找出任何字符串的索引號(hào)。
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()
此方法返回一個(gè)新字符串,其中包含給定字符串的指定副本數(shù)。
Syntax: repeat(count);Example:Let str=’Bangladesh’console.log(str.repeat(3));Result: ` Bangladesh Bangladesh Bangladesh `
6、split()
此方法用分隔符分割字符串并返回一個(gè)數(shù)組。當(dāng)字符串為空時(shí),split() 方法返回一個(gè)包含一個(gè)空字符串的數(shù)組。
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() 方法從字符串中刪除開(kāi)頭和結(jié)尾的所有空白并返回一個(gè)新字符串。
Syntax: trim()Example:const greeting = ' Hello world! ';console.log(greeting);Result: `Hello world`
8、toString()
此方法將字符串轉(zhuǎn)換為任何對(duì)象。它返回一個(gè)表示指定對(duì)象的字符串。
Syntax: toString();Example:let str = new String('Hello world');console.log(str.toString());Result: `Hello world`;
9、toUpperCase()
此方法用于將字符串值轉(zhuǎn)換為大寫并返回一個(gè)新字符串。
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() 方法用于將任何字符串轉(zhuǎn)換為小寫并返回一個(gè)新字符串。
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."
感謝你的閱讀。
學(xué)習(xí)更多技能
請(qǐng)點(diǎn)擊下方公眾號(hào)
![]()

評(píng)論
圖片
表情
