常规的字符串操作,拼接字符串使用字符串模板,获取字符串里面的数据(chatAt)、字符串截取(substring、slice),字符串转array(split),字符串去除空格(trim replace(正则表达式))
判断是否是字符串
let str = "taowuhua"typeof strconsole.log(typeof str)
获取字符串某下表的字符
charAt() 方法从一个字符串中返回指定的字符,常用在遍历字符串的每一位数据
str.charAt(index)
let str = "taowuhua"for (let index = 0; index < str.length; index++) {const element = str.charAt(index)console.log(element)}
获取Unicode 编码单元
str.charCodeAt(index)
"ABC".charCodeAt(0) // returns 65"ABC".charCodeAt(1) // returns 66
当前字符串是否是以另外一个给定的子字符串“结尾”
str.endsWith(searchString);注意区分大小写
const str1 = 'Cats are the best';console.log(str1.endsWith('best'));// expected output: trueconst str2 = 'Is this a question';console.log(str2.endsWith('?'));// expected output: false
判断一个字符串是否包含在另一个字符串;
注意区分大小写
'Blue Whale'.includes('Blue'); // returns true'Blue Whale'.includes('haha'); // returns false
**indexOf()** 方法返回调用它的 String 对象中第一次出现的指定值的索引,从 fromIndex 处进行搜索。如果未找到该值,则返回 -1
console.log('hello world'.indexOf('e'))console.log('hello world'.indexOf('n'))
slice() 方法提取某个字符串的一部分,并返回一个新的字符串
注意:返回一个新的字符串
const str = 'The quick brown fox jumps over the lazy dog.';console.log(str.slice(31));// expected output: "the lazy dog."console.log(str.slice(4, 19));// expected output: "quick brown fox"
字符串转数组
**split() **方法使用指定的分隔符字符串将一个String对象分割成子字符串数组
注意:返回一个字符串数组
var str = '2019-02-01'str.split('-')console.log(str.split('-'))
截取字符串
substring()方法返回一个字符串在开始索引到结束索引之间的一个子集
var anyString = "Mozilla";// 输出 "Moz"console.log(anyString.substring(0,3));
字符串值转为小写形式
console.log('中文简体 zh-CN || zh-Hans'.toLowerCase());// 中文简体 zh-cn || zh-hansconsole.log( "ALPHABET".toLowerCase() );// "alphabet"
字符串值转为大写形式
const sentence = 'The quick brown fox jumps over the lazy dog.';console.log(sentence.toUpperCase());// expected output: "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."
删除字符串两端空白字符
const greeting = ' Hello world! ';console.log(greeting);// expected output: " Hello world! ";console.log(greeting.trim());// expected output: "Hello world!";
根据正则表达式返回新的字符串
str.replace(regexp)
字符串是否匹配正则表达式
str.match(regexp)
当参数是一个字符串或一个数字
var str = "Nothing will come of nothing.";str.match(); // returns [""]str1.match("number"); // "number" 是字符串。返回["number"]str1.match(NaN); // NaN的类型是number。返回["NaN"]
正则表达式和 String 对象之间的一个搜索匹配
str.search(regexp)
返回正则表达式在字符串中首次匹配项的索引;否则,返回 -1。
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';// any character that is not a word character or whitespaceconst regex = /[^\w\s]/g;console.log(paragraph.search(regex));// expected output: 43console.log(paragraph[paragraph.search(regex)]);// expected output: "."
