字符串的常用方法和属性

159 阅读2分钟

创建字符串的方法

  1. 字面量方法 var str='123'
  2. 构造函数方法 var str= new String('123')

字符串属性

  • length字符串的长度

字符串常用方法

  • charAt() 根据索引返回内容
var str='hello'
var newStr=str.charAt(0)
console.log(newStr)
//值为h
  • indexOf()根据内容返回索引
var str='hello'
var newStr=str.indexOf('o')
console.log(newStr)
//返回值为4
  • lastIndexOf()根据内容返回索引,倒着查找
var str='ohello'
var newStr=str.lastindexOf('o')
console.log(newStr)
//返回结果为5

  • substring(a,b)截取字符串a为从那儿开始,b为从那儿结束,不包括结束位置,不影响源字符串,返回新的字符串
var str='hello'
var newStr=str.subString(0,2)
console.log(newStr)
//返回结果为h
  • substr(a,b)截取字符串a为起始位置,b为到那儿结束,包括结束位置,不影响源字符串,返回新的字符串
var str='hello'
var newStr=str.substr(0,2)
console.log(newStr)
//返回结果为he
  • concat(a)连接字符串,不影响原字符串,返回新字符串
var str='hello'
var newStr=str.concat(' word')
console.log(newStr)
//返回结果为hello word
  • split(a)分隔字符串,里面参数为分隔的字符串类型,不填写则按个分割,不影响原字符串,返回一个数组,
var str='hello'
var newStr=str.split('')
console.log(newStr)
//返回结果为['h','e','l','l','o']
  • repalce(a,b)替换字符串a为查找的字符,b为替换的值
var str='hello word'
var newStr=str.replace('word','JavaScript')
console.log(newStr)
//返回的结果为 hello JavaScript

-trim()清除字符串空格,返回新字符串

var str='  helloword'
var newStr=str.trim()
console.log(newStr)
//返回的结果为hello JavaScript
  • toLowerCase()将字符串里面的值转换为小写,返回新字符串
var str='HELLO'
var newStr=str.toLowerCase()
console.log(newStr)
//返回的结果为hello
  • toUpperCase()将字符串转换为大写,返回新字符串
var str='hello'
var newStr=str.toUpperCase()
console.log(newStr)
//返回的结果为HELLO
  • startsWith(a)查找字符串以什么开头,满足条件返回true|false
var str='hello'
var newStr=str.startsWith('h')
console.log(newStr)
//返回的结果为true
  • endsWith(a) 查找字符串以什么结束,满足条件返回true|false
var str='hello'
var newStr=str.endsWith('o')
console.log(newStr)
//返回的结果为true
  • includes()检查数组是否包含其内容,返回true|false
var arr=['hello','word']
var newArr=arr.includes('word')
console.log(newArr)
//返回的结果为true