javascript String类型基本方法

String类型的常用方法

  1. charAt()、charCodeAt() 访问字符串特定字符的方法,两个的区别就是输出的结果不同,charCodeAt()输出的是Unicode 编码
let str = 'you are my shine'
console.log(str.charAt(1))  // o
console.log(str.charCodeAt(6)) // 101
  1. substring() 截取字符串,接受两个参数,第一个是起始位置,第二个是结束位置
let str = 'you are my sunshine'
console.log(str.substring(0))  // you are my sunshine
console.log(str.substring(1,6))  // ou ar
  1. substr() 截取字符串,接受两个参数,第一个是起始位置,第二个截取的字符个数
let str = 'you are my sunshine'
console.log(str. substr(0))  // you are my sunshine
console.log(str. substr(1,6))  // ou are
  1. slice() 截取字符串,但是可以有负数,表示从末尾开始截取字符
let str = 'you are my sunshine'
console.log(str.slice(1, 9))  // ou are m
console.log(str.slice(-5, -1))  // shin
  1. concat() 拼接字符串
let str = 'you are my'
let str2 = ' sunshine'
console.log(str.concat(str2))  // you are myshine
  1. indexOf() 定位字符
let str = 'you are my shine'
console.log(str.indexOf('are')) // 4
  1. match() 匹配字符串,涉及到正则
let str = 'you are my shine'
console.log(str.match(/e/g))  // ['e', 'e']
let str1 = '我是1你是2'
console.log(str.match(/\d+/g))   // ['1', '2']
  • 注: 返回的是数组
  1. replace() 替换字符,第一个参数是正则,第二个更换成的字符
let str = 'you are my sunshine'
console.log(str.replace(/are/, 'are always')) //  you are always my sunshine
console.log(str.replace(/e/g, ';'))  // you ar; my sunshin;
  1. search() 搜索,返回的是字符(串)的位置
let str="you are my sunshine"
console.log(str.search(/are/))  // 4
  1. split() 分割字符串,返回的数组
let str="you are my sunshine"
console.log(str.split(' '))  // ['you','are','my','sunshine']
  1. toLowerCase() 转成小写
let str="YOU ARE MY SUNSHINE"
console.log(str.toLowerCase())  //you are my sunshine
  1. toUpperCase() 转成大写
let str="you are my sunshine"
console.log(str.toUpperCase())  // YOU ARE MY SUNSHINE
  1. toLocaleLowerCase()、toLocaleUpperCase()这两种方法一般很少使用,与toLowerCase()、toUpperCase()不同的是,将会按照本地方式把字符串转换成小写。

感谢您的view,留个赞再走呗

  • 感谢浏览姑娘的文章,来自一个写前端的姑娘!
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容