Nodejs基礎系列-07- javascript 字符串處理

//字符串處理
//01-常用轉義
//單引號轉義\'
let s1="I\'am like footbool!"
console.log(s1); //I'am like footbool!
//雙引號 \"
let s2="I \"think\" I \"am\" "
console.log(s2) ;//I "think" I "am"
//反斜槓 \\
let s3="one\\two\\three"
console.log(s3);//one\two\three
//換行符 \n
let s4="I am \nI happy "
console.log(s4);
//I am
//I happy
//製表符/\t
let s5="one\ttwo\tthree"
console.log(s5);//one  two three

//02-合併字符串 concat
let word1="Today ";
let word2="is ";
let word3="Sunday";
let wordconstr1=word1+word2+word3;
let wordconstr2=word1.concat(word2,word3);
console.log(wordconstr1);//Today is Sunday
console.log(wordconstr2);//Today is Sunday


//03-在字符串中搜索字符串 indexOf (第一次出現的位置)
let myStr="In the past five years, I\'am found a good  five path.";
if(myStr.indexOf("five")!=-1){
    console.log(myStr.indexOf("five"))//12
    console.log(myStr);//In the past five years, I'am found a good  five path.
}

//lastIndexOf  (最後一次出現的位置)
if(myStr.lastIndexOf("five")!=-1){
    console.log(myStr.lastIndexOf("five"))//43
 }


//04-字符串分割成數組 split
let strdtr="2020:02:01";
let arr_dtr=strdtr.split(":");
console.log(arr_dtr[0]);//2020
console.log(arr_dtr[1]);//02
console.log(arr_dtr[2]);//01

//05-charAt(index)返回指定索引出的字符
console.log(myStr.charAt(10)); //t   注意從0開始。

//06-charCodeAt(index)返回指定索引處字符的unicode值
console.log(myStr.charCodeAt(10)) //116

//07-replace(subString/regex,replacementString)
//搜索字符串或正則表達式匹配,並用新的字符串替換配置的字符串(注意:僅替換第一次出現的)
let myStr_rp= myStr.replace("five","six");
console.log(myStr_rp);//In the past six years, I'am found a good  five path.


//把字符串中所有"five" 替換成了"six"
while (myStr.indexOf("five")!=-1){
    myStr=myStr.replace("five","six");
}
console.log(myStr);//In the past six years, I'am found a good  six path.


//08-返回 slice(start,end)返回start和end(不含)之間的一段新字符串
let myStr_btw="long long ago there was a king";
console.log(myStr_btw.slice(1,12));//ong long ag

//09-substr(start,length) 從指定位置開始按照指定長度提取字符串
console.log(myStr_btw.substr(0,13));//long long ago

//10-substring(from ,to) 返回字符索引from與to(不含)之間的子串,與slice結果一樣
console.log(myStr_btw.substring(1,12));//ong long ag

//11-大小寫轉換 toUpperCase()轉大寫;  toLowerCase()轉小寫
console.log(myStr_btw.toUpperCase());//LONG LONG AGO THERE WAS A KING
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章