示例字符串:
const str = "hello,kitty,hello,vue ";
charAt() 返回指定索引的字符 startsWith() 判断字符串是否以xxx开头,返回布尔值 endsWith() 判断字符串是否以xxx结尾,返回布尔值 padStart() 头部补全,返回新字符串 padEnd() 尾部补全,返回新字符串 repeat() 拷贝字符串,返回新字符串 toUpperCase() 大写转换,返回新字符串 toLowerCase() 小写转换,返回新字符串
用例:
charAt() console.log(str.charAt(1)); // h trim() console.log(str.trim()); // hello,kitty,hello,vue startsWith() / endsWith() console.log(str.startsWith("hello")); // true padStart() / padEnd() str.padStart(number,string) 接收两个参数,第一个指定补全后的字符串长度,第二个可选,用来补全的字符串。默认补全空格 console.log(str.padStart(5,"x")); // hello,kitty,hello,vue 原本的长度超过了5,所以补不全 console.log(str.padStart(30,"x")); // xxxxxxxxhello,kitty,hello,vue 原本的长度少于30,缺多少补多少 console.log(str.padStart(30)); // hello,kitty,hello,vue repeat() str.repeat(number)接收一个参数,复制的份数 console.log(str.repeat(2)); // hello,kitty,hello,vue hello,kitty,hello,vue toUpperCase() / toLowerCase() console.log(str.toUpperCase()); // HELLO,KITTY,HELLO,VUE
indexOf() 返回字符串中指定文本首次出现的索引,不存在返回-1 lastIndexOf() 返回字符串中指定文本最后一次出现的索引.如果不存在返回-1 search() 字符串内搜索特定值,返回第一次出现的索引,如果没有返回-1。与indexOf()的区别是,可以使用正则表达式, match() 字符串内检索指定的值,或找到一个或多个正则表达式的匹配。(通过字符串或正则表达式)。返回数组或null includes() 【es6新增】判断字符串中是否包含指定文本,返回布尔值
示例:
indexOf() / lastIndexOf() indexOf(string,start) 为匹配的字符串,start为开始匹配的索引,默认为0 console.log(str.indexOf("5")); // -1 console.log(str.indexOf("e")); // 1 search() console.log(str.search("o")); // 4 match() console.log(str.match("e")); // ["e"] 属性有:length,index,input console.log(str.match(/ell/g)); // ["ell","ell"] includes() console.log(str.includes("vue")); // true console.log(str.includes("react")); // false
substring() 根据索引截取字符串,返回新字符串 substr() 根据起始索引和长度截取。返回新字符串 slice() 根据索引截取,返回新字符串。与substring()不同的是,参数可以传入负值 trim() 去除首尾空格,返回新字符串 trimRight() 去除右侧空格,返回新字符串 trimLeft() 去除左侧空格,返回新字符串
用例:
substring() str.substring(start,end) 起始索引和结束索引。第一个参数必需,第二个非必需 console.log(str.substring(1)); // ello,kitty,hello,vue 从索引1开始到结束 console.log(str.substring(1,4)); // ell 从索引1到索引3的字符串 substr() str.substr(start,length) 传入一个开始索引和截取长度 console.log(str.substr(1,10)); // ello,kitty 从索引1开始截取长度为10的字符串 slice() str.slice(start,end) 根据索引,与substring不同的是,可以传入负值。如果参数为负值,表示从字符串的结尾开始计数。这里需要注意,如果传入负值,也遵从start在坐,end在右的规则。示例如下 console.log(str.slice(-7,-3)); // lo,v console.log(str.slice(-3,-7)); // 空
concat() 可拼接多个字符串,返回新的字符串 split() 将字符串分割成数组 join() 将数据转成字符串
用例:
let str1 = "abc",str2 = "def"; let arr = [1,2,3,4,5]; console.log(str.concat(str1,str2)); // hello,kitty,hello,vue abcdef console.log(str.split(",")); // ["hello", "kitty", "hello", "vue "] console.log(arr.join("-")); // 1-2-3-4-5
replace() 根据字符串或正则表达式进行替换,返回新字符串 let re = "/hello/g", re2 = "/hello/", re3 = "hello"; str.replace(re,"React"); // React,kitty,React,vue str.replace(re2,"React"); // React,kitty,hello,vue str.replace(re3,"React"); // React,kitty,hello,vue
原文:https://www.cnblogs.com/V587Chinese/p/11404916.html