Nodejs基础系列-07- javascript 字符串处理

本文深入讲解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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值