js中的String對象操作

//length 屬性返回字符串的長度(字符數)
var str = "hello world";
 console.log(str.length);
//indexOf()	返回指定字符在字符串中首次出現的位置
var url = 'http://127.0.0.1:3000/api/hook/list/308.shtml';//實現取得308
console.log(url.indexOf('/')); 
//lastIndexOf() 返回指定字符在字符串中最後出現的位置
var url = 'http://127.0.0.1:3000/api/hook/list/308.shtml';//實現取得308
console.log(url.lastIndexOf('/')); //35
console.log(url.lastIndexOf('.')); //39
console.log(url.substring(url.lastIndexOf('/')+1,url.lastIndexOf('.'))); //308
//string.substr(start[,length]) 返回從start位置開始截取length長度的字符串,如果length省略,則截取到最後,如果start爲負數,則是從最後數起
var str="Hello world!";
console.log(str.substr(2)); //llo world!
console.log(str.substr(2,6)); //llo wo
console.log(str.substr(-2)); //d!
console.log(str.substr(-2,1)); //d
console.log(str.substr(-2,2)); //d!
//string.substring(start[,end]) 返回從start位置開始到end位置結束的字符,包括start位置的字符,但不包括end位置的字符,start與end要求爲非負整數,
//如果end大於字符串最後一個字符的位置,則會忽略end參數
var name = 'jiangzunshao';
console.log(name.substring(1)); //iangzunshao 說明:省略end,截取到最後
console.log(name.substring(1,2)); //i 說明:包括start位置的字符,但不包括end位置的字符
console.log(name.substring(1,20)); //iangzunshao 說明:end大於字符串最後一個字符的位置,則忽略end參數
//string.replace(search,new) 在字符串中查找search匹配的子串,使用new替換與search匹配的子串
var str="Mr Blue has a blue house and a blue car";
console.log(str.replace(/blue/,"red")); //Mr Blue has a red house and a blue car
console.log(str.replace(/blue/g,"red")); //Mr Blue has a red house and a red car 說明:g全局匹配,並替換
console.log(str.replace(/blue/gi,"red")); //Mr red has a red house and a red car 說明:g全局匹配,i忽略大小寫
//string.toLowerCase() 把字符串轉換爲小寫
var email = "[email protected]";
console.log(email.toLowerCase()); //[email protected]
//toUpperCase()	把字符串轉換爲大寫
console.log(email.toUpperCase()); //[email protected]
// charAt()	返回在指定位置的字符
var str = "HELLO WORLD";
console.log(str.charAt(2)); //L
// charCodeAt()	返回在指定的位置的字符的 Unicode 編碼
console.log(str.charCodeAt(2)); //76
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章