.concat() | .slice() | .split() | .repeat()
- str.concat(str2, [, ...strN]) 将一个或多个字符串和原字符串连接合并,返回新的字符串,不影响原字符串。
let greetList = ['hello','','world','!']
"".concat(...greetList)
"".concat({})
"".concat([])
"".concat(null)
- str.slice(beginIndex[, endIndex]) 从索引(beginIndex)处开始提取字符到endIndex(可选)结束,返回新的字符串,不会改动原字符串。
Index为负值,会被当做strLength+Index
let str = 'the morning'
str.slice(1,4)
str.slice(7)
str.slice(1,-1)
str.slice(-3)
str.slice(-3,-1)
- str.split([separator[, limit]])使用指定的分隔符字符串(separator)将str对象分割为子字符串数组,用limit(可选)限定返回的分割片段数量。
let string = "hello world. play with js"
string.split(" ")
string.split(" ", 2)
let string = 'ca,bc,a,bca,bc'
string.split(['a','b'])
- str.repeat(count) 复制count次str,并将副本连接在一起返回一个新字符串
count是非负的整数,且返回值长度不能大于最长的字符串
"abc".repeat(0)
"abc".repeat(2)
"abc".repeat(3.5)
"abc".repeat(-1)
.includes() | .indexOf() | .lastIndexOf()
- str.includes(searchString, position)执行区分大小写的搜索,确定是否可以在str中找到searchString,position(可选)是在str中开始搜索searchString的位置,结果返回true或false
const str = "To be"
str.includes("To be")
str.includes("to be")
str.includes("To", 1)
str.includes("")
- str.indexOf(searchString, position)在str中区分大小写搜索searchString,若position不为0,则从position位置开始搜索,返回它第一次出现的索引位置
const str = "hello World"
str.indexOf("hello")
str.indexOf("Hello")
str.indexOf("hello", 1)
str.indexOf("hello", -1)
str.indexOf('', 3)
str.indexOf('', 12)
- str.lastIndexOf(searchValue[, fromIndex])从字符串str的fromIndex或结尾处搜索searchValue,即在str的指定位置从后向前区分大小写的搜索,返回searchValue在str中最后一次出现的索引
const str = 'canal'
str.lastIndexOf('a')
str.lastIndexOf('na')
str.lastIndexOf('a', 2)
str.lastIndexOf('a', 0)
str.lastIndexOf('a', -5)
str.lastIndexOf('a', 12)
str.lastIndexOf('')
str.lastIndexOf('', 2)
.match() | .matchAll() | .replace() | .replaceAll() | .search()
- str.match(regexp)检索返回一个字符串匹配正则表达式的结果
let str = 'ABCDEFGabcdefg'
let regexp = /[A-E]/gi
let matchs = str.match(regexp)
str.match()
- str.matchAll(regexp)返回一个包含所有正则表达式的结果及分组捕获组的迭代器
- str.replace(regexp|substr, newSubStr|function)返回由替换值替换匹配项后的新字符串
- regexp 正则表达式,所匹配的内容会被第二个参数返回值替换
- substr 被替换的字符串,仅第一个匹配项会被替换
- newSubStr 用于替换的字符串
- function 创建新字符串的函数
let str = 'hello world'
let newStr = str.replace('world', 'new world')
let newStr1 = str.replace(/world/i, 'new world')
let re = /(\w+)\s(\w+)/
let newStr2 = str.replace(re, "$2,$1")
- str.replaceAll(regexp|substr, newSubStr|function)返回一个所有满足匹配项都被替换值替换的新字符串
- str.search(regexp)返回正则表达式在字符串中首次匹配项的索引
let str = 'hello World'
let re = /[A-Z]/g
str.search(re)
let re1 = /[.]/g
str.search(re1)