常规的字符串操作,拼接字符串使用字符串模板,获取字符串里面的数据(chatAt)、字符串截取(substring、slice),字符串转array(split),字符串去除空格(trim replace(正则表达式))

判断是否是字符串

  1. let str = "taowuhua"
  2. typeof str
  3. console.log(typeof str)

获取字符串某下表的字符

charAt() 方法从一个字符串中返回指定的字符,常用在遍历字符串的每一位数据
str.charAt(index)

  1. let str = "taowuhua"
  2. for (let index = 0; index < str.length; index++) {
  3. const element = str.charAt(index)
  4. console.log(element)
  5. }

获取Unicode 编码单元

str.charCodeAt(index)

  1. "ABC".charCodeAt(0) // returns 65
  2. "ABC".charCodeAt(1) // returns 66

当前字符串是否是以另外一个给定的子字符串“结尾”

str.endsWith(searchString);注意区分大小写

  1. const str1 = 'Cats are the best';
  2. console.log(str1.endsWith('best'));
  3. // expected output: true
  4. const str2 = 'Is this a question';
  5. console.log(str2.endsWith('?'));
  6. // expected output: false

判断一个字符串是否包含在另一个字符串;

注意区分大小写

  1. 'Blue Whale'.includes('Blue'); // returns true
  2. 'Blue Whale'.includes('haha'); // returns false

**indexOf()** 方法返回调用它的 String 对象中第一次出现的指定值的索引,从 fromIndex 处进行搜索。如果未找到该值,则返回 -1

  1. console.log('hello world'.indexOf('e'))
  2. console.log('hello world'.indexOf('n'))

slice() 方法提取某个字符串的一部分,并返回一个新的字符串

注意:返回一个新的字符串

  1. const str = 'The quick brown fox jumps over the lazy dog.';
  2. console.log(str.slice(31));
  3. // expected output: "the lazy dog."
  4. console.log(str.slice(4, 19));
  5. // expected output: "quick brown fox"

字符串转数组

**split() **方法使用指定的分隔符字符串将一个String对象分割成子字符串数组
注意:返回一个字符串数组

  1. var str = '2019-02-01'
  2. str.split('-')
  3. console.log(str.split('-'))

截取字符串

substring()方法返回一个字符串在开始索引到结束索引之间的一个子集

  1. var anyString = "Mozilla";
  2. // 输出 "Moz"
  3. console.log(anyString.substring(0,3));

字符串值转为小写形式

  1. console.log('中文简体 zh-CN || zh-Hans'.toLowerCase());
  2. // 中文简体 zh-cn || zh-hans
  3. console.log( "ALPHABET".toLowerCase() );
  4. // "alphabet"

字符串值转为大写形式

  1. const sentence = 'The quick brown fox jumps over the lazy dog.';
  2. console.log(sentence.toUpperCase());
  3. // expected output: "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."

删除字符串两端空白字符

  1. const greeting = ' Hello world! ';
  2. console.log(greeting);
  3. // expected output: " Hello world! ";
  4. console.log(greeting.trim());
  5. // expected output: "Hello world!";

根据正则表达式返回新的字符串

  1. str.replace(regexp)

字符串是否匹配正则表达式

str.match(regexp)
当参数是一个字符串或一个数字

  1. var str = "Nothing will come of nothing.";
  2. str.match(); // returns [""]
  3. str1.match("number"); // "number" 是字符串。返回["number"]
  4. str1.match(NaN); // NaN的类型是number。返回["NaN"]

正则表达式和 String 对象之间的一个搜索匹配

str.search(regexp)
返回正则表达式在字符串中首次匹配项的索引;否则,返回 -1

  1. const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
  2. // any character that is not a word character or whitespace
  3. const regex = /[^\w\s]/g;
  4. console.log(paragraph.search(regex));
  5. // expected output: 43
  6. console.log(paragraph[paragraph.search(regex)]);
  7. // expected output: "."