Js字符串常用方法
目录
简介
字符串有两种形式 基本类型 和 对象类型
对象类型的字符串封装了一些属性方法
‘aaa’.length = 3 // error 字符串的长度 不能改变
字符串的== , ===
// ==, === 判断
console.log(1 == '1') // true
console.log(1 === '1') // false
str.charAt(index)
/**
* str.charAt(index)
* 功能:获取对应下标的字符
* @param index number
*/
console.log('abc'.charAt(0)) // a
str.toLowerCase()/toUpperCase()
/**
* str.toLowerCase() str.toUpperCase()
* 功能:转换大小写
* 不改变源
* */
console.log('AAA'.toLowerCase())
console.log('aaa'.toUpperCase())
str.indexOf(str, startIndex)/lastIndexOf(str, startIndex)
/***
* str.indexOf(str, stratIndex) str.lastIndexOf(str, startIndex)
* 功能:从左往右查找第一次出现的字符串/从右忘左 默认从最左/右开始
* @param str string 要查找的字符串
* @param startIndex? number 从那个下标开始查找
* @return 子串第一次出现的下标
* 不改变源
*/
let str1: string = 'abc==abc==abccc=abc'
// 统计str1 出现某个只窜的个数
let countStr: (str: string, num: number, count: number) => number = (str, num, count) => {
let nowNum: number = str1.indexOf(str, num)
if (nowNum != -1) {
return countStr(str, nowNum + str.length, ++count)
} else {
return count
}
}
console.log(countStr('abc', 0, 0))
console.log(str1.lastIndexOf('abc')) // 16
str.replace(oldStr, newStr)
/**
* str.replace(oldStr: string, newStr: string)
* 功能:用新字符串替换目标字符串
* @param oldStr string
* @param newStr string
* @return string 替换后的字符串
* tips: 使用正则可以全部替换
* 不改变源
*/
let str2: string = '我爱你-我爱他'
console.log(str2.replace('爱', '不爱')) // 我不爱你-我爱他
console.log(str2.replace(/爱/g, '不爱')) // 我不爱你-我不爱他
console.log(str2) // 我爱你-我爱他
str.substring(startIndex, endIndex)
/**
* str.substring(startIndex, endIndex)
* 功能:提取字符串介于两个指定下标之间的字符
* @param startIndex number 开始的坐标
* @param endIndex number 不会包含这个坐标的字符
* @return string 截取的字符串
* 不会改变源
*/
let str3: string = 'are is be'
console.log(str3.substring(4, 6)) // is
console.log(str3) // are is be
console.log(str3.substring(4)) // is be
console.log(str3.substring(3, 0)) // are // 如果start 比end大 会交换
str.substr(start, num)
/**
* str.substr(start, num)
* 功能:抽取从start开始的num个字符
* @param start number 负数就从后面开始
* @param start number
* @return string 截取的字符串
* 不会改变源
*/
let str4: string = "are is be"
console.log(str4.substr(0, 3)) // are
console.log(str4.substr(-2, 2)) // be
str.split(str, number)
/**
* stt.split(str, number)
* 功能: 分割字符串 成数组
* @param str string 分割标识
* @param number number 数组最大长度
* @return array
* 不会改变源
*/
console.log('i=1=dad=42'.split('=')) // ["i", "1", "dad", "42"]
console.log('i=1=dad=42'.split('=', 2)) //["i", "1"]
str.concat(str1, str2 …)
/**
* str.concat(str1, str2 ...)
* 功能: 合并字符串
* @param str string 要合并的字符串
* @return string 合并后的字符串
* 不会改变源
*/
console.log('123'.concat('4,5,6', '789')) // 1234,5,6789
str.trim()
/**
* str.trim()
* 功能去字符串前后空格
* @return string 处理后的字符串
*/
console.log(' as d '.trim()) // as d
模版字符串
let s:string = 'a'
console.log(`${s}bc`) // abc