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
发布了40 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/LUCKWXF/article/details/104136604