js字符串方法
| 方法 | 参数 | 参数为一个 | 参数都为正 | 参数为负 | |
| slice | 接收的是起始位置和结束 位置(不包括结束位置) | 省略结束位置参数,从参数位置开始截取 到字符串结束,负参数从左开始往右截取 | 起始位置大于结束位置, 返回空 | 参数都为负: 从负参数开始截取到负参数结束(起始位置<结束位置) (起始位置>结束位置)//报错 开始为正,结束为负: 从正参数开始截取到负参数结束 开始为负,结束为正:返回为空 | |
| substring | 参数中有负值,将其转化成0。两个参数中较小的一个作为起始位置。 | ||||
| substr | 接收的是起始位置和所要 返回的字符串长度 | 和slice一样 | 返回字符串长度不能为负值(没有意义)。 如果参数为负,相当于截取字符串长度为0. | ||
var str="good good study";
var res=str.replace(/GOOD/ig,"day");//day good study(默认匹配首个字符串)2.全局替换:
var str="good good study";
var res=str.replace(/GOOD/g,"day");//day day study四、转化为大写或小写:
toUpperCase():将都有字符串中的字母都转化成大写;
toLowerCase():将都有字符串中的字母都转化成小写;
var str="good good study";
console.log(str.toUpperCase());//全部转化大写(GOOD GOOD STUDY)
console.log(str.toLowerCase());//全部转化小写(good good study)五、连接两个字符串或多个concat()
var one="hello",two="world",three="!!!";
var x=one.concat("+","abc",three);
console.log(x)//hello abc !!!
var x=one.concat("+",two,three);
console.log(x)//hello world !!!
//--代替连接符
var x= "hello".concat(" ","world");
var x= "hello".concat(" ","world"," ","world");
console.log(x)//hello world world六、删除字符串两端的空白trim()
//删除字符串两端的空白符trim()
var str = " Hello World! ";
console.log(str.trim());//Hello World;
//去左空格;
/*function ltrim(s){
return s.replace(/(^\s*)/g,"");//去除左空格
}*/
//去右空格;
/*function rtrim(s){
return s.replace(/(\s*$)/g,"");//去除右空格
}*/
console.log(ltrim(str));七、提取字符串字符charAt(i)
var str = "HELLO WORLD";
console.log(str.charAt(0)); //H八、返回字符串中指定索引的字符 unicode 编码
var str = "HELLO WORLD";
console.log(str.charCodeAt(0));//72 var txt = "at,b,cpp,d,e"; // 字符串
var test=txt.split(","); // 用逗号分隔
var test1=txt.split(" "); // 用空格分隔
var test2=txt.split("|"); // 用竖线分隔
console.log(test);//返回数组[0:at,1:b,···]
//如果字符串之间没有符号
var txt = "H,ello"; // 字符串
var txt_= txt.split("");// 分隔为字符
console.log(txt_); //返回数组[0:H,1:,,···]
var a=txt_.join("");//数组转化成字符串
console.log(txt_); //H,ello练习:
//查找字符串中有多少个e
var str="there is no challess there will be no success";
var sum=0;
for(var i=0;i<str.length;i++){
if(str.charAt(i)=="e"){sum+=1};
}
console.log(sum)
//正则表达式查找有多少个e
var str="there is no challess there will be no success";
var res=str.match(/e/g);
console.log(res.length);
//查找字符串中任意字符串(查找第二个good)
var str="good good study";
function indexof(str1,str2,num){//str1字符串,str2查找的字符串,num查找的第几个(0代表第一个)
var res=str.indexOf(str2);
for(var i=0;i<num;i++){
res=str1.indexOf(str2,res+1);
}
return res
}
console.log(indexof(str,"good",1));
//替换第二个good
var str="good good good study";
function rep_str(str1,str2,str3,num){//str1字符串,str2需要替换的字符串,str3替换的字符串,num替换的第几个
var sum=0;
var strall=str.split(" ");
for( var i=0; i<str.length;i++){
if(strall[i]==str2){
sum+=1;
if(sum==num){
strall[i]=str3
}
}
}
var res=strall.join(" ");
return res
}
console.log(rep_str(str,"good","day",2));本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!