1. 程式人生 > >字符串方法總結

字符串方法總結

tin style arch 一次 則表達式 表達式 var unicode ring1

var str="hello girl";
// charAt() (返回指定位置的字符,index從0開始)
console.log(str.charAt(1)); //e (返回指定位置的字符,index從0開始)

// charCodeAt() 返回字符串指定位置字符的 Unicode 編碼
console.log(str.charCodeAt(1)); //101 (返回字符串指定位置字符的 Unicode 編碼,index從0開始)

// string.concat(string1, string2, ..., stringX) 連接字符串
var a="my name ";
var b="is lss , ";
var c="nice to meet you";
console.log(a.concat(b));//my name is lss (連接兩個字符串,該方法沒有改變原有字符串,但是會返回連接兩個或多個字符串新字符串。)
console.log(a.concat(b,c));//my name is lss , nice to meet you (連接多個字符串)

// indexOf() 第一次出現e的位置
console.log(c.indexOf("e"));//3 第一次出現e的位置
console.log(c.indexOf("ee"));//9 第一次出現ee的位置

// string.lastIndexOf(searchvalue,start) 指定的字符串值最後出現的位置
console.log(c.lastIndexOf("e"));//10 最後一次出現ee的位置
console.log(c.lastIndexOf("e",8));//3 從8位置開始往前找,最後一次出現ee的位置

// str.replace(a,b) 將a字符串替換成b
var d="Wxx is a wxx";
console.log(b.replace("lss","wxx"));//is wxx ,
console.log(d.replace(/wxx/g,"dog"));//Wxx is a dog ,
console.log(d.replace(/wxx/gi,"dog"));//dog is a dog , 忽略大小寫:

// string.search(searchvalue) 查找的字符串或者正則表達式相匹配的 String 對象起始位置
var e="blankDog is a dog";
console.log(e.search("dog"));//14
console.log(e.search(/dog/i));//5 不區分大小寫 查找的字符串或者正則表達式相匹配的 String 對象起始位置

// str.slice(start,end) 截取start-end的字符串 包括start不包括end
console.log(e.slice(5,8));//Dog 截取5-8的字符串 包括5不包括8
console.log(e.slice(-3,-1));//do 截取倒數第二個到第三個,不包括第四個

// string.split(separator,limit) 字符串分割
console.log(e.split());//["blankDog is a dog"]
console.log(e.split(" "));// ["blankDog", "is", "a", "dog"]
console.log(e.split(" ",3));// ["blankDog", "is", "a"]返回的數組的最大長度為3
console.log(e.split(" ")[0]);//blankDog

// string.substr(start,length) 在字符串中抽取從 start開始的指定length的字符
console.log(e.substr(5,3));//Dog 從5開始向後取3個字符
console.log(e.substr(-3,3));//dog 從倒數第三個開始向後取3個字符

// string.substring(from, to) 提取字符串中介於兩個指定下標之間的字符
console.log(e.substring(9));//is a dog 從9開始提取後面字符串
console.log(e.substring(9,11));//is 從9到11提取兩個字符
console.log(e.toUpperCase());//BLANKDOG IS A DOG 將e字符串所以字符變成大寫
console.log(e.toLowerCase());//blankdog is a dog 將e字符串所以字符變成小寫

// trim() 去除字符串兩邊的空白
var f=" lucydog is not a dog ";
console.log(f.trim()); //lucydog is not a dog 去除字符串兩邊的空白

字符串方法總結