ES6字符串方法
Es6引入了String对象的新方法。在这篇博文中,我将通过实例介绍新的字符串方法
新引入的字符串方法可以是通用方法和Unicode方法
通用方法
- startsWith()
- endsWith()
- 包括()
- 重复()
String.prototype.startsWith()方法示例
startsWith()方法返回
true - 如果通过的字符串与搜索字符串从起始索引位置开始匹配,如果指定了索引位置,则从第n个位置开始检查。
false - 搜索字符串没有被匹配
语法
startsWith(searchstring,index)
两个参数是:1.要搜索的字符串 - 要搜索的子串 2. 索引位置 - 它是搜索开始的位置。默认为零
const message = "This is a new string methods";
console.log(message.startsWith("This is")); // true
console.log(message.startsWith("Thias is")); // false
console.log(message.startsWith("is", 4)); // false
console.log(message.startsWith("is", 5)); // true
String.prototype.endsWith()方法示例
endsWith()方法也需要两个参数
如果字符串的末尾与其他字符串匹配,该方法将返回true。
语法
endsWith(searchstring,index)
它有两个参数 1.Search string - 从末端开始搜索匹配的字符串 2.2.索引位置 - 这是一个要与字符串匹配的位置,这是可选的。
const message = "This is a new string methods";
console.log(message.endsWith("methods")); // true
console.log(message.endsWith("methodsa is")); // false
console.log(message.endsWith("is", 4)); // true
console.log(message.endsWith("is", 5)); // false
String.prototype.includes()方法示例
如果搜索的子串包含在一个字符串中,该方法返回true。
includes(searchstring,index)
它有两个参数 1.Search string - 要与给定的字符串匹配的字符串 2.索引位置 - 这是开始搜索字符串的起始位置,这是可选的。
const message = "this is tesing include";
console.log(message.includes("tesing")); // true
console.log(message.includes("adfadf")); // false
console.log(message.includes("is", 8)); // false
console.log(message.includes("is", 2)); // true
String.prototype.repeat()方法示例
该方法重复给定的字符串的次数。它给出了串联字符串的输出结果
参数 - 重复字符串的次数。
const message = "cloud";
console.log(message.repeat(2)); // cloudcloud
console.log(message.repeat(3)); // cloudcloudcloud