1.字符方法:
str.charAt(): 可以訪問字符串中特定的字符,可以接受0至字符串長度-1的數字作為參數,返回該位置下的字符,如果參數超出該范圍,返回空字符串,如果沒有參數,返回位置為0的字符;
str.charCodeAt(): 和charAt()用法一樣,不同的是charCodeAt()返回的是字符編碼而不是字符。
var anyString="hello tino"; anyString.charAt() //"h" anyString.charAt(2) //"l" anyString.charAt(18) //""
2.字符串操作方法:
字符串拼接:
最常用的就是字符串拼接,可以用"+“操作符連接兩個字符串,或者用concat()方法,concat()方法接受一個或多個字符串參數,返回拼接后得到的新字符串,需要注意的是concat()方法不改變原字符串的值。
var str="hello tino"; var nstr=str.concat(" and nick"); console.log(str); // “hello tino” console.log(nstr); // "hello tino and nick"
基於子字符串創建新字符串:
slice() 接受一到兩個參數,第一個參數是指定字符串的開始位置,第二個參數是字符串到哪里結束(返回的字符串不包括該位置),如果沒有第二個參數,則將字符串的末尾作為結束位置。如果不傳參數,返回原字符串。slice()方法也不會改變原有字符串
var str="hello tino"; str.slice(5,9) // "tino" str.slice(5) //"tino" str.slice() //"hello tino"
substr()方法和slice()方法一樣,不同在於參數是負值時,slice()方法會將傳入的負值與字符串長度相加,substr()會將第一個負值相加,第二個負值參數轉換為0;
var str="hello tino"; console.log(str.slice(-4)); // "tino" console.log(str.substr(-4)); //"tino" console.log(str.slice(1,-4)); //"ell" console.log(str.substr(1,-4)); // ""
substring()方法也接受兩個參數,與前兩不同,substring()第二個參數是表示字符的個數。
3.字符串位置方法:
indexOf(),參數為子字符串,從左至右查找,返回子字符串位置,如果沒找到該子字符串,返回-1。
lastIndexOf(),參數為子字符串,從右至左查找,返回子字符串位置,如果沒找到該子字符串,返回-1。
這兩個方法接受可選的第二個參數(整數),表示從該位置開始搜索。
var str="hello tino"; str.indexOf("o") //4 str.lastIndexOf("o") //9
4.trim()方法
該方法創建一個字符串的副本,刪除前置和后綴的所有空格。
5.大小寫轉換
toLowerCase() ,創建原字符串的小寫副本
toUpperCase() ,創建原字符串的大寫副本