字符串相关方法

查找字符串

indexOf()、lastIndexOf()
/**
 * indexOf() -- 从前往后第一次出现,第二个参数表示查找的起始位置
 * lastIndexOf() -- 从后往前最后一次出现
 * 获取字符串中指定内容的索引 -- 找到返回对应索引,找不到返回-1
 */
var str = 'hello world'
console.log(str.indexOf('o')) //4
console.log(str.lastIndexOf('o')) //7
console.log(str.indexOf('b')) //-1
console.log(str.indexOf('o', 5)) //7
/**
 * 查找字符串"qianguyihao",所有a出现的次数和位置
 */
var str = 'qianguyihao'
var index = str.indexOf('a')
var num = 0
while (index !== -1) {
  console.log(index)
  num++
  index = str.indexOf('a', index + 1)
}
console.log(num)
search()
/**
 * search() 获取字符串中指定参数的索引(参数一般为正则)
 * 找到返回第一次出现的索引,找不到返回-1
 */
var str = 'hello world'
console.log(str.search('wo')) //6
console.log(str.search(/wo/i)) //6
console.log(str.search(/ol/i)) //-1
includes()
/**
 * 字符串中是否包含指定内容
 * 参数opsition,表示查找的起始位置
 * 包含返回true,否则返回false
 */
var str = 'hello world'
console.log(str.includes('llo')) //true
console.log(str.includes('oll')) //false
console.log(str.includes('wo', 3)) //true
startsWith()、endsWith()
/**
 * startsWith() -- 是否以指定的内容开头
 * endsWith() -- 是否以指定的内容结尾
 * 是返回true,否返回false
 * 第二个参数为匹配的起始位置
 */
var str = 'hello world'
console.log(str.startsWith('he')) //true
console.log(str.endsWith('ld')) //true
console.log(str.startsWith('el', 3)) //false

获取指定位置字符

charAt()
/**
 * charAt(index)
 * 获取指定位置的字符
 * H5标准新增特性 str[index],其和str.charAt(index)同
 */
var str = 'hello world'
console.log(str.charAt(6)) //w
console.log(str.charAt()) //h
console.log(str.charAt(20)) // 空
charCodeAt(index)
/**
 * charCodeAt(index)
 * 获取指定位置的字符的Unicode编码
 * 一般用来判断用户按下了哪个按键
 */
var str = 'hello world'
console.log(str.charCodeAt(6)) //119
console.log(str.charCodeAt()) //104
console.log(str.charCodeAt(20)) //NaN
/**
 * 判断一串字符串的占位长度
 * 英文占位一个字符
 * 中文占位两个字符
 */
var str = 'hello world love and peace 我爱你中国'
function JudgeLen(string) {
  let count = 0
  for (var i = 0; i < string.length; i++) {
    // 在0-127为英文字符,占一,其他为2
    if (string.charCodeAt(i) < 128 && string.charCodeAt(i) >= 0) {
      count++
    } else {
      count += 2
    }
  }
  return count
}
console.log(JudgeLen(str))

字符串截取

slice()、substring()
/**
 * slice(开始位置,结束位置)
 * substring(开始位置,结束位置)
 * substring与slice类似,但默认不接受负值,接受负值,当0处理
 * substring还可以自动调整参数位置,如果第二个小于第一个,自动交换
 */
var str = 'hello world'
console.log(str.slice(2, 5)) //llo
console.log(str.substring(2, 5)) //llo
console.log(str.slice(2)) //llo world
console.log(str.substring(2)) //llo world
console.log(str.slice(-3)) //rld
console.log(str.substring(-3)) //hello world -- (0)
console.log(str.slice(1, -1)) //ello worl
console.log(str.substring(1, -1)) //h -- (0,1)
console.log(str.slice(5, 2)) //空
console.log(str.substring(5, 2)) //llo -- (2,5)
substr()
/**
 * substr(开始索引,截取的长度)
 * 不改变原字符串
 * ECMAscript没有对其标准化,不建议使用
 */
var str = 'hello world'
console.log(str.substr(1, 3)) //ell
console.log(str.substr(1)) //ello world
console.log(str.substr(-3)) //rld

padStart()、padEnd()

/**
 * JS字符串补全
 * padStart()用于头部补全,padEnd()用于尾部补全。
 */
console.log('1'.padStart(2, '0')) // 01
console.log('1'.padEnd(2, '0')) //10

string.fromCharCode()

/**
 * String.fromCharCode()
 * 根据字符的Unicode编码获取字符
 */
console.log(String.fromCharCode(72)) //H
console.log(String.fromCharCode(20013)) //中

concat()

/**
 * str1.concat(str2)
 * 用于两个字符串的链接,一般不用,直接相加
 * 数组也用concat,用于数组连接
 */
var str1 = 'hello '
var str2 = 'world'
var arr1 = [1, 2, 3]
var arr2 = [4, 5, 6]
console.log(str1.concat(str2)) // hello world
console.log(arr1.concat(arr2)) // [ 1, 2, 3, 4, 5, 6 ]

split()

/**
 * 新的数组 = str.split(分割符)
 * 将字符串转换为数组,不改变原字符串
 * 一般用于从后台拿到json数据后的转化
 */
var str = 'love,and,peace'
console.log(str.split(',')) //[ 'love', 'and', 'peace' ]

replace()

/**
 * 字符串替换
 * 新的字符串 = str.replace(被替换的字符串,新的字符串)
 * 返回新内容,不会修改原字符串
 */
var str = 'Today is fine day,today is not tomorrow'
console.log(str.replace('today', 'now')) //Today is fine day,now is not tomorrow
console.log(str.replace(/today/gi, 'now')) //now is fine day,now is not tomorrow

repeat()

/**
 * repeat 重复字符串
 * 新字符串 = str.repeat(重复次数)
 */
var str1 = 'hello'
console.log(str1.repeat(2)) //hellohello
var str2 = '15532776825'
console.log(str2.slice(0, -4) + '*'.repeat(4)) //1553277****

trim()

/**
 * trim()
 * 去除字符串首尾空白
 */
var str = ' a b c '
console.log(str) // a b c
console.log(str.length) //7
console.log(str.trim()) //a b c
console.log(str.trim().length) //5

toLowerCase()、toUpperCase()

/**
 * 大小写转化
 * toLowerCase() -- 转小写
 * toUpperCase() -- 转大写
 */
var str = 'regGUP'
console.log(str.toLowerCase()) //reggup
console.log(str.toUpperCase()) //REGGUP
console.log(str.slice(0, 1).toUpperCase() + str.slice(1)) //RegGUP

html 方法

/**
 * html方法
 */
var str = 'hello world'
console.log(str.anchor('bing')) //<a name="bing">hello world</a>
console.log(str.big()) //<big>hello world</big> -- h5不支持
console.log(str.sub()) //<sub>hello world</sub>
console.log(str.sup()) //<sup>hello world</sup>
console.log(str.link('cn.bing.com')) //<a href="cn.bing.com">hello world</a>
console.log(str.bold()) //<b>hello world</b>

练习

/**
 * 查找字符串中所有m出现的位置
 * smyhvaevaesmyh
 */
var str = 'smyhvaevaesmyh'
// 第一种
var index = str.indexOf('m')
while (index !== -1) {
  console.log(index) // 1 11
  index = str.indexOf('m', index + 1)
}

//第二种
for (var i = 0; i < str.length; i++) {
  if (str.charAt(i) === 'm') {
    console.log(i) //1 11
  }
}

/**
 * 判断一个字符串中出现次数最多的字符
 * 统计这个次数
 * smyhvaevaesmyh
 */
var str1 = 'smyhvaevaesmyhvae'
var json = {}
for (i = 0; i < str1.length; i++) {
  var key = str1.charAt(i)
  if (json[key] === undefined) {
    json[key] = 1
  } else {
    json[key] += 1
  }
}
console.log(json)
var maxValue = 0
var maxChar = ''
for (let v in json) {
  if (json[v] > maxValue) {
    maxValue = json[v]
    maxChar = v
  }
}
console.log('出现最多字符为:' + maxChar + ' ,出现次数为:' + maxValue)

for…in vs for…of

/**
 * for...in  vs for...of
 * for...in遍历时取得key和index -- 适合遍历对象;遍历数组顺序不固定
 * for...of遍历时取得value -- 适合遍历数组
 * for...of循环适合遍历map、set、数组对象、字符串等有迭代器对象的集合,不能遍历普通对象
 * ES5增加forEach用于数组的遍历,但不能正确响应break、continue、return语句,for...of可以
 * 如果想要对普通对象进行遍历,用for...in或内建Object.keys()
 */
var str = {
  name: 'falcon',
  age: 21,
  sex: '女',
}
var arr = ['Chinese', 'Math', 'English']
var arr1 = [
  {
    id: 1,
    name: 'falcon',
    lesson: 'Chinese',
  },
  {
    id: 2,
    name: 'alice',
    lesson: 'Math',
  },
  {
    id: 3,
    name: 'jerry',
    lesson: 'English',
  },
]

for (let v in str) {
  console.log(v) //name age sex
  console.log(str[v]) //falcon 21 女
}
for (let v in arr) {
  console.log(v) //0 1 2
  console.log(arr[v]) //Chinese Math English
}
for (let v in arr1) {
  console.log(v) //0 1 2
  console.log(arr1[v]) //每个对象
}
// for (let v of str) {
//   console.log(v); 报错str is not iterable,因为没有迭代器对象
// }
for (let v of arr) {
  console.log(v) //Chinese Math English
}
for (let v of arr1) {
  console.log(v) //遍历出每个对象
}

注:以上所有方法总结和案例参考“千古壹号”web 自学路线资料总结

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值