首页 > 编程语言 > 详细

javaScript字符串方法

时间:2019-08-27 22:18:18      阅读:87      评论:0      收藏:0      [点我收藏+]
        var str = "9z好hello world!";
     根据索引获取字符
var res = str.charAt(3); console.log(res);
     根据索引取字符编码
var res = str.charCodeAt(0); console.log(res);
     把编码传化成字符串
var res = String.fromCharCode(111); console.log(res); var str = "hello weorld!";
     查找字符在字符串中第一次出现的位置,如果没有返回-1
var res = str.indexOf(a); console.log(res);
     查找字符在字符串中最后一次出现的位置,如果没有返回-1
var res = str.lastIndexOf(e); console.log(res);
     转换成大写
var res = str.toUpperCase(); console.log(res, str);      转换成小写 var res1 = res.toLowerCase(); console.log(res1);

 

字符串方法:

  •  charAt(index)—— 根据索引获取字符;
  • charCodeAt(index)—— 根据索引获取字符的编码;
  • String.fromCharCode(code) ——把编码转换成字符;
  • indexOf(char)—— 查找字符在字符串中第一次出现的索引,如果不存在返回-1;
  • lastIndexOf(char) ——查找字符在字符串中最后一次出现的索引,如果不存在返回-1;
  •  toUpperCase()—— 转换成大写;
  •  toLowerCase()—— 转换成小写;
  • substring(star,end)—— 复制字符串中的指定字符;
    var str = "hello weorld!";
           var res = str.substring(2); // 从索引2开始复制到末尾
           console.log(res);
           var res = str.substring(2,4);  // 从索引2开始复制到索引4,不包含4
           console.log(res);
           var res = str.substring(4,2); // 自动交换位置  (2,4)
           console.log(res);
           var res = str.substring(-3,4); //  负数当0处理 (0,4)
           console.log(res);

     

  • slice()——复制字符串中指定字符
           var res = str.slice(2); // 从索引2开始复制到末尾
           console.log(res);
           var res = str.slice(2,4); // 从索引2开始复制到索引4,不包含4
           console.log(res);
           var res = str.slice(4,2); //前面数大,结果为 ‘‘
           console.log(res);
           var res = str.slice(-10,4);  // -10+长度 (3,4)
           console.log(res);
           var res = str.slice(-6,4);  // -10+长度 (7,4)  前面数大,结果为 ‘‘
           console.log(res);

     

  • split()——以分割符分割成数组
           var str = "hel,lo weo-rld www qqq";
           var res = str.split();   //没有参数,不分割,整体放入数组
           console.log(res);   //["hel,lo weo-rld www qqq"]
           var res = str.split(‘‘);//参数为空字符串,每个字符都单独分割
           console.log(res);  //["h", "e", "l", ",", "l", "o", " ", "w", "e", "o", "-", "r", "l", "d", " ", "w", "w", "w", " ", "q", "q", "q"] 
           var res = str.split( );//参数为空格,以空格字符分开
           console.log(res); //["hel,lo", "weo-rld", "www", "qqq"]
           var res = str.split(/[, -]/);//以多个字符(逗号,空格,连字符的位置都断开)分割字符串
           console.log(res); // ["hel", "lo", "weo", "rld", "www", "qqq"]

     

  • replace(old,new)——用新的字符串替换旧的字符串
           var str = "hello weorld";
           var res = str.replace(e,E);
           console.log(res);  // ‘hEllo weorld‘;只替换一个
    
           var str = "heelo weorld";
           var res = str.replace(/e/g,E); // 有几个e就替换几个
           console.log(res); //‘hEElo wEorld‘

     

 

javaScript字符串方法

原文:https://www.cnblogs.com/musong-out/p/11420836.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!