字串的方法

2021-10-01 17:29:21 字數 2368 閱讀 4160

//字串方法

將字串轉化為小寫

// touppercase() 將字串轉化為大寫

var str="hello";

var stra=str.tolowercase();//轉換小寫

console.log(stra);//hello

var strb=str.touppercase();//轉換大寫

console.log(strb);//hello

console.log(str);//hello

獲取指定下標處的字元

// charcodeat() 獲取指定下標出的unicode的碼

將unicode的碼轉化為對應字元

var str="aa愛你";

var str1=str.charat(2); // 獲取指定下標處的字元 提取陣列中的內容

console.log(str1);// 愛

var str2=str.charcodeat(0);// 獲取指定下標出的unicode的碼

console.log(str2);//a轉換為 97

var str3=string.fromcharcode(str2);//把數字再轉換為unicode碼 97轉換為a

//將unicode的碼轉化為對應字元

console.log(str3);// a

指定字串,開始查詢的位置) 返回第一次指定字串的下標(左--》右)

// lastindexof(指定字串,[開始查詢的位置]) 返回最後一次指定字串的下標(右---》左)

// 開始查詢的位置:

//預設0(indexof()) 預設最後(lastindexof())

//結果返回-1,未找到

var str="hello world";

console.log(str.length);//11

console.log(str);

console.log(str.indexof("e")); // 1

console.log(str.indexof("el"));// 1 只取第乙個e的下標 後面l不取

console.log(str.indexof("o")); // 4

console.log(str.indexof("o",5));//7 取o後面重複的 5是正著數 然後是上面的4加一

console.log(str.lastindexof("o"));//7倒著數

console.log(str.lastindexof("o",6));//4倒著數然後後面的6是上面的7減一

console.log(str.indexof("a"));//因為沒有a所以沒有的內容全轉換為-1

//4. slice()獲取子字串

//slice(開始下標,[真正的結束=結束下標-1])

// 獲取子字串,含頭不含尾

//如果只有開始將獲取後面所有的內容

//可以取負值,最後乙個數是-1,往前推(-2,-3...)

var str="hello world";

var str1=str.slice(1,4);// ell

var str1=str.slice(-10,-7);// ell

var str1=str.slice(3);// lo world

console.log(str1);// ell

//substring()獲取子字串,不能取負值

var str2=str.substring(1,4);

console.log(str2);// ell

//substr(開始位置,擷取的長度) 獲取子字串,能取負值

var str3=str.substr(2,7);

var str3=str.substr(-11,7);// hello w

console.log(str3);// llo wor

// 5.split(分隔符,[保留個數]) 分隔字串,轉化為陣列

var str="||aa||bb||cc";

var arr=str.split("||",4);

console.log(arr);// ["", "aa", "bb", "cc"]

// 6.concat() 拼接字串/ +

var str="aa";

var arr=str.concat("bb","cc") ;

console.log(arr);// aabbcc

var str="11";

var arrr="11"+"22"+"33";

console.log(arrr);// 112233

字串及字串的方法

一 字串 js中的任何資料型別都可以當作物件來看。所以string既是基本資料型別,又是物件。二 宣告字串 var sstr 字串 var ostr new string 字串 三 字串屬性 1.length計算字串的長度 不區分中英文 var str hello world console.log...

字串的方法

獲取 int length 獲取長度 char charat int index 獲取位置上的某個字元 int indexof int ch 因為接受的是asc 碼,返回的是ch在字串中出現的第一次位置 int indexof int ch,int fromindex 從fromindex指定位置獲...

字串的方法

1.charat 下標 作用 查詢該下標位置處的字元,返回乙個字元 2.charcodeat 下標 作用 查詢該下標位置處的字元的unicode編碼 3.fromcharcode 作用 根據乙個unicode編碼值返回對應的字元,與charcodeat 結果相反 4.indexof 作用 查詢某個字...