1.indexOf()查找該字符串的位置
(1)不存在一律返回-1;
(2)有第二個參數,表示下標
var str = "hello world";
console.log(str.indexOf('l'));//2
console.log(str.indexOf('l',5));//9
2.lastIndexOf()返回一個指定的字符串值最后出現的位置,在一個字符串中的指定位置從后向前搜索。
(1)不存在同樣返回-1;
(2)同樣有第二個參數,表示從該下標的位置開始往前找。
var str = "hello world";
console.log(str.lastIndexOf('l'));//9
console.log(str.lastIndexOf('l',6));//3
3.slice()提取字符串的某個部分,有第二個參數,前閉后開
參數:兩個
第一個 指定開始提取的位置
第二個 指定提取結束的位置。
1,提取的范圍包括開始位置,但是不包括結束位置。
2,如果省略第二個參數,表示從開始位置提取到字符串結束。
3,不會比較兩個參數的大小關系。
4,如果沒有參數,默認提取整個字符串。
5,參數只能為整數(正、負、零),非法參數會解析成0.
var str = "hello world";
console.log(str.slice(6));//world
console.log(str.slice(3,7);//lo w
4.split()用于把一個字符串分割成字符串數組
*第2個參數可選。該參數可指定返回的數組的最大長度。如果設置了該參數,返回的子串不會多于這個參數指定的數組。如果沒有設置該參數,整個字符串都會被分割,不考慮它的長度。
var str = "Hello World";
console.log(str.split('1'));//["Hello World"]
console.log(str.split('l'));//["he", "", "o wor",? ? "d"]
var str = "a-b-c-d-e-f-g";
console.log(str.split('-',3));//["a", "b", "c"]
5.substring()提取相應區間的字符
*substring(starIndex,endIndex)
參數:兩個
第一個 指定開始提取的位置
第二個 指定提取結束的位置。
1,提取的范圍包括開始位置,但是不包括結束位置。
2,如果省略第二個參數,表示從開始位置提取到字符串結束。
3,在提取之前會先比較兩個參數的大小,然后按從小到大的順序調整兩個參數的位置,再提取。
4,如果沒有參數,默認提取整個字符串。
5,參數只能為正整數,非法參數會解析成0.
var str = "a-b-c-d-e-f-g";
console.log(str.substring(3,6));//-c-(截取的字符串長? ? 度為6-3,從3開始,不包含6)
6.charCodeAt()返回指定下標位置的字符Unicode編碼
var str = 'abc'.charCodeAt(0);//括號內表示下標
console.log(str);//a的Unicode編碼是97,b98,c99
7.charAt()返回指定位置的字符
參數:一個? 指定要獲取的字符位置。 如果不設置參數,默認獲取第一個位置上的字符
var str = 'abc'.charAt(0);
console.log(str);//a
8.toUpperCase()/toLowerCase() 把字符串轉化為大/小寫
var str1 = "hello world";
console.log(str1.toUpperCase());//HELLO WORLD
var str2 = "HELLO WORLD";
console.log(str2.toUpperCase());//hello world
9.replace() 方法在字符串中用某些字符替換另一些字符。
var? str = " Please visit Microsoft!" ;
var str2 =? str.replace("Microsoft","w3cschool");
10.trim()去掉字符串前后的空格
不兼容低版本IE瀏覽器
str = "? abc def ghi? ? ";
str2 = str.trim();
console.log(str2);//abc def ghi
那要想保留字符串前面的空格,只去掉后面的空格呢?看下面:
str = " abc def ghi ";
console.log(str.length)//13
str2 = ("a"+str).trim().substring(1);
console.log(str2);// abc def ghi
console.log(str2.length);//12