1)字串的识别
ES6 之前判断字符串是否包含子串,用 indexOf 方法,ES6 新增了子串的识别方法
includes():返回布尔值,判断是否找到参数字符串。
let string = "apple,banana,orange";
string.includes("banana"); // true
startsWith():返回布尔值,判断参数字符串是否在原字符串的头部。
startsWith() 方法用于检测字符串是否以指定的子字符串开始
如果是以指定的子字符串开头返回 true,否则 false
startsWith() 方法对大小写敏感
该方法可以传两个参数,参数一(必要):需要查找的字符串,参数二:开始查找的位置
let string = "apple,banana,orange"
string.startsWith("apple") // true
string.startsWith("banana",6) // true
endsWith():返回布尔值,判断参数字符串是否在原字符串的尾部。
endsWith():返回布尔值,判断参数字符串是否在原字符串的尾部。
startsWith() 方法用于检测字符串是否以指定的子字符串结束
如果是以指定的子字符串结尾返回 true,否则 false
endsWith() 方法对大小写敏感
该方法可以传两个参数,参数一(必要):需要查找的字符串,参数二:该字符串结束的位置
let string = "apple,banana,orange"
string.endsWith("ge") // true
string.startsWith("b",6) // true
注意
-
这三个方法只返回布尔值,如果需要知道子串的位置,还是得用 indexOf 和 lastIndexOf 。
-
这三个方法如果传入了正则表达式而不是字符串,会抛出错误。而 indexOf 和 lastIndexOf 这两个方法,它们会将正则表达式转换为字符串并搜索它。
2)字符串重复
repeat():返回新的字符串,表示将字符串重复指定次数返回
console.log("Hello,".repeat(2))
// "Hello,Hello,"
如果参数是小数,向下取整
console.log("Hello,".repeat(3.2))
// "Hello,Hello,Hello,"
如果参数是 0 至 -1 之间的小数,会进行取整运算,0 至 -1 之间的小数取整得到 -0 ,等同于 repeat 零次
console.log("Hello,".repeat(-0.5))
// ""
如果参数是 NaN,等同于 repeat 零次
console.log("Hello,".repeat(NaN))
// ""
如果参数是负数或者 Infinity ,会报错:
console.log("Hello,".repeat(-1))
// RangeError: Invalid count value
console.log("Hello,".repeat(Infinity))
// RangeError: Invalid count value
如果传入的参数是字符串,则会先将字符串转化为数字
console.log("Hello,".repeat("hh"))
// ""
console.log("Hello,".repeat("2"))
// "Hello,Hello,"
3)字符串补全
-
padStart:返回新的字符串,表示用参数字符串从头部补全原字符串。
-
padEnd:返回新的字符串,表示用参数字符串从尾部补全原字符串。
以上两个方法接受两个参数
第一个参数是指定生成的字符串的最小长度
第二个参数是用来补全的字符串。如果没有指定第二个参数,默认用空格填充。
console.log("h".padStart(5,"o")) // "ooooh"
console.log("h".padEnd(5,"o")) // "hoooo"
console.log("h".padStart(5)) // " h"
如果指定的长度小于或等于原字符串的长度,则返回原字符串:
console.log("hello".padStart(5,"A"))
// "hello"
如果原字符串加上补全字符串长度大于指定长度,则截去超出位数的补全字符串:
console.log("hello".padEnd(10,",world!"))
// "hello,worl"
常用于补全位数:
console.log("123".padStart(10,"0"))
// "0000000123"
4)模板字符串
1.普通字符串
var str=`abc`
console.log(str)
2.多行字符串
var str=`udgfugf
sdkhdlksfh
dksfhksh`
3.插入代码(引用变量,调用函数)
var a="123"
console.log(`和我一起读${a}吧`)
//和我一起读123吧
function myfunction(){
return "123"
}
console.log(`好的,${myfunction()}`)
//好的,123
注意
模板字符串中的换行和空格都是会被保留的
5)标签模板
标签模板,是一个函数的调用,其中调用的参数是模板字符串。
alert`Hello world!`
// 等价于
alert('Hello world!')