js-06-字符串

一、查找字符串的字符串

a:indexOf:没有查询到返回值为-1;

b:lastIndexoOf:查找到的为重复的最后一个;

c:search 查找;

var str="good good study";
//a:
console.log(str.indexOf("study"));         //10
//b:
console.log(str.lastIndexOf("good");     //5
//c:
console.log(str.search("study"));      

 二、提取部分字符串

方法 参数 参数为一个 参数都为正 参数为负 
slice

接收的是起始位置和结束

位置(不包括结束位置)

省略结束位置参数,从参数位置开始截取

到字符串结束,负参数从左开始往右截取

起始位置大于结束位置,

返回空

扫描二维码关注公众号,回复: 7075078 查看本文章

参数都为负:

从负参数开始截取到负参数结束(起始位置<结束位置)

(起始位置>结束位置)//报错

开始为正,结束为负:

从正参数开始截取到负参数结束

开始为负,结束为正:返回为空

substring 参数中有负值,将其转化成0。两个参数中较小的一个作为起始位置。
substr

接收的是起始位置和所要

返回的字符串长度

和slice一样  

返回字符串长度不能为负值(没有意义)。

如果参数为负,相当于截取字符串长度为0.

  a:slice  console.log(str.slice(5,2))

  b:substring(取负参从零开始)  console.log(str.substring(3,7));

  c:substr(规定长度)  console.log(str.substr(3,7));

三、替换字符串内容

格式:replace("旧的字符串","新字符串")

var str="good good study";
var res=str.replace("good","day");
console.log(res);
console.log(str);                      //返回原字符串不受影响四

 四、正则表达式匹配 

var str="good good study";
var res=str.replace(/Good/i,"day");

  注:"/ /i"(单独替换) → 对大小写不敏感,忽略大小写。

     "/ /g" (全局替换) → 全局替换

五、字母转换大小写

console.log(str.toUpperCase());//全部转化大写
console.log(str.toLowerCase());//全部转化小写 

六、连接两个或多个字符串(concat)

var one="hello";
var two="world";
var three="!!!"
var x=one.concat("+","abc",three);
console.log(x) 

七、删除字符串两端的空白符trim()

var str = "       Hello World!        ";
console.log(str.trim());
//去左空格;
    function ltrim(s){
    return s.replace(/(^\s*)/g,"");
}
//去右空格;
    function rtrim(s){
    return s.replace(/(\s*$)/g,"");
}  

八、提取字符串字符charAt(0)

var str = "HELLO WORLD";
console.log(str.charAt(0)); 

九、返回字符串中指定索引的字符 unicode 编码

var str = "HELLO WORLD";
console.log(str.charCodeAt(0));  

 十、把字符串转换为数组split()

var txt = "at,b,cpp,d,e";   // 字符串
var test=txt.split(",");          // 用逗号分隔
var test1=txt.split(" ");          // 用空格分隔
var test2=txt.split("|");          // 用竖线分隔	
console.log(test1);

  

 练习:

//查找字符串中有多少个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);
 

猜你喜欢

转载自www.cnblogs.com/fengyinghui/p/11377890.html