slice(startIndex,endIndex) 剪切字符,返回新字符
- 不包括endIndex的字符
- 原字符不变
- 第二个参数如没有,切剩余全部
- 第二个参数如为负数,表示尾端切掉几个
const str = 'abced'
console.log(str.slice(1,2))
console.log(str.slice(1))
console.log(str.slice(1,-1))
substr(startIndex,count) 剪切字符,返回新字符
const str = 'abced'
console.log(str.substr(1,2), str)
console.log(str,substr(1))
substring(startIndex,endIndex) 剪切字符,返回新字符
- 原字符不变
- 不包括endIndex字符
- 剪切个数为endIndex-startIndex
- 如果endIndex小于startIndex,会交换位置
- 不接受负数
const str = 'abced'
console.log(str.substring(1,3))
console.log(str.substring(3,1))
chartAt(index) 返回字符
console.log('abc'.charAt('1'))
indexOf('') lastIndexOf('') 返回索引
- indexOf 从左到右找
- lastIndexOf 从右到左找
'abc'.indexOf('b')
'abcc'.lastIndexOf('c')
concat('') 返回新字符串
console.log("abc".concat("ef"))
split('') 返回数组
console.log("a*b*c".split("*"))
console.log('abc'.split())
toLowerCase() 返回小写字符串
const str = "AbC"
console.log(str.toLowerCase(), str)
toUpperCase() 返回大写字符串
const str = "AbC"
console.log(str.toUpperCase(), str)
includes('') 返回布尔
const str = 'abced'
console.log(str.includes('b'))
startsWith('') 返回布尔
console.log('abc'.startsWith('a'))
endsWith('') 返回布尔
console.log('abc'.endsWith('a'))
trim() 返回新字符串
console.log(' 1 23 '.trim())
repeat(number) 返回新字符串
console.log('abc'.repeat(2))
match(正则/指定字符) 返回数组
const str = "2018年结束了,2019年开始了,2020年就也不远了"
console.log(str.match("20"))
console.log(str.match(/\d+/g))
replace(被替换字符/正则,替换字符/回调函数) 返回新字符串
- 原字符不变
- 如果第一个参数为字符串,只能匹配第一个
const str = "2018年结束了,2019年开始了,2020年就也不远了"
console.log(str.replace("20", "?"), str)
console.log(str.replace(/\d+/g, "!"))
const rs = str.replace(/\d+/g, function (item) {
return "?"
})
console.log(rs)
search(正则) 返回索引
const str = "2018年结束了,2019年开始了,2020年就也不远了"
console.log(str.search(/\d+/g))
字符转义
- 判断空格,正则匹配str.replace(/ /g, "?") 空格都替换为问号
- 定义带有换行的字符用`` 不是普通的单双引号。
':单引号
":双引号
\:反斜杠
\n:换行
\r:回车
\t:制表符
\b:退格
\f:换页
let str = "这是一个包含\"双引号\"的字符串";
console.log(str);
const str = `abc
sfsdf
ddf
`
console.log(str)
console.log(JSON.stringify(str).replace(/ /g, "\?"))