String对象用于处理文本
一、String对象常用方法
1、concat():连接字符串,注:使用‘+ 运算符来进行字符串连接更简便
2、charAt(index):返回指定位置的字符,如果参数 index 不在 0 与 string.length 之间,该方法将返回一个空字符串
3、str.indexOf(searchString,startIndex):返回子字符串第一次出现的位置,从startIndex开始查找,找不到时返回-1
4:str.lastIndexOf(searchString,startIndex): 从由往左找子字符串,找不到时返回-1**
5、截取字符串的三种方法
substring(start,end) :提取字符串中介于两个指定下标之间的字符
substr(start,length):
slice(start,end) :提取字符串的某个部分,并以新的字符串返回被提取的部分
注:String 对象的方法 slice()、substring() 和 substr() (不建议使用)都可返回字符串的指定部分。slice() 比 substring()
要灵活一些,因为它允许使用负数作为参数。slice() 与 substr() 有所不同,因为它用两个字符的位置来指定子串,而 substr()
则用字符位置和长度来指定子串
6、str.split(separator,number):字符串分隔成数组,第二个参数表示返回的字符串数组的最大长度(可选)
7 、str.replace(rgExp/substr,replaceText) : 执行的是查找并替换的操作, 返回替换后的字符串,如果 regexp 具有全局标志 g,那么 replace() 方法将替换所有匹配的子串。否则,它只替换第一个匹配子串
var str="Visit Microsoft!"
console.log(str.replace(/Microsoft/, "W3School")) // Visit W3School!
//全局替换
var str = "welcome to Microseft"
str=str + "We are proud to announce that Microsoft has "
str=str + "one of the largest Web Developers sites in the world."
console.log(str.replace(/ Microsoft/g,"W3School"))
//Welcome to W3School! We are proud to announce that W3School
//has one of the largest Web Developers sites in the world.
待解决问题:如何使用replace把单词的首字母转换成大写?
把单词的首字母转换成大写的几种方式?
8、str.match(rgExp): 正则匹配,在字符串内检索指定的值,或找到一个或多个正则表达式,该方法类似 indexOf() 和 lastIndexOf(),但是它返回指定的值,而不是字符串的位置
9、search():方法的用法等同于match,但是返回值为匹配的第一个位置。如果没有找到匹配,则返回-1
9、trim():去除字符串收尾两端的空格,返回一个新的字符串,不改变原字符串
10、toLowerCase(),toUpperCase():toLowerCase方法用于将一个字符串全部转为小写,toUpperCase则是全部转为大写。它们都返回一个新字符串,不改变原字符串。
ES6新增常见扩展
1、为字符串添加了遍历器接口,使得字符串可以被for…of循环遍历。
2、**includes(), startsWith(), endsWith() **
1:includes():返回布尔值,表示是否找到了参数字符串
2:startsWith():返回布尔值,表示参数字符串是否在原字符串的头部
3:endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。
注:以上三个方法均支持第二个参数,表示开始搜索的位置,includes(), startsWith()表示从第n个位置直到结束,endsWith()表示前n个字符
var str = "hello world!"
console.log(str.includes("w",6)); // true
console.log(str.includes("w",7)); // false
console.log(str.startsWith("h")); //true
console.log(str.endsWith("!")) // true
3、repeat(n):返回一个新字符串,将原字符串重复n次,如果n是小数,会被取整,n是负数或者Infinity,会报错
4、padStart(),padEnd():ES2017 引入了字符串补全长度的功能。如果某个字符串不够指定长度,会在头部或尾部补全。padStart()用于头部补全,padEnd()用于尾部补全
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'
'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'
5、matchAll()
6、**模板字符串 **:用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量
// 普通字符串
`In JavaScript '\n' is a line-feed.`
// 多行字符串
`In \`JavaScript\` this is
not legal.`
console.log(`string text line 1
string text line 2`);
// 字符串中嵌入变量
let name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
如果在模板字符串中需要使用反引号,则前面要用反斜杠转义
模板编译(实例)
let template = `
<ul>
<% for(let i=0; i < data.supplies.length; i++) { %>
<li><%= data.supplies[i] %></li>
<% } %>
</ul>
`;
上面代码在模板字符串之中,放置了一个常规模板。该模板使用<%…%>放置 JavaScript 代码,使用<%= … %>输出 JavaScript 表达式