关于字符串的那点事儿(二)

15 阅读1分钟

字符串中常用的API

1、toLowerCase() toUpperCase() 转换大小写,返回新的字符串

 var str1 = 'Hello World';
 console.log(str1.toLowerCase());
 console.log(str1.toUpperCase());

2、charAt(index) 根据索引获取字符串中的某一个字符

 console.log(str1.charAt(1));  //e

3、charCodeAt(index) 根据索引获取字符串中的某一个字符的ASCII编码

console.log(str1.charCodeAt(1)); 
在此附上ASCII编码的对照表: ASCII编码对照表

4、startswith() endswith() 判断字符串是否以某个字符或字符串开头/结尾,返回布尔值

 console.log(str1.startsWith('Hello')); //true
 console.log(str1.endsWith("ld")); //true

5、include(str , startIndex) 判断一个字符串中是否包含某个字符串,返回布尔值

参数1:要查找的字符或字符串
参数2:从那个位置开始查找
console.log(str1.includes('Hello')); //true
var str2 = 'hello,你好,hello'
console.log(str2.includes('hello',10));

6、trim() 去除字符串两端的空格

  var str3 = '   你  好    ';
  console.log(str3);
  console.log(str3.trim());

在软件内输出,查看效果。

7、replace(oldstr,newstr) 替换字符串中的某一部分,返回新的字符串

console.log(str1.replace('World',"世界"));

8、split('/') 以某一特殊字符,将字符串分割为数组。

 var str4 = '苹果-香蕉-橘子';
 console.log(str4.split('-'));

9、substr(startindex,lenght) 截取字符串

 var str5 = 'aabhellohcchdd';
 console.log(str5.substr(3,5)); //hello

10、indexOf() 查询指定字符在字符串中第一次出现的索引

 console.log(str5.indexOf('h'));   //5  查询h在str5中第一次出现的索引号
 console.log(str5.indexOf('h',5));  //8  从指定位置查询 h 在 str5中第一次出现的索引号。
 // lastIndexOf()(反向查找)查询指定字符在字符串中最后一次出现的位置
 console.log(str5.lastIndexOf('h',10)); //8
字符串常用的东西大概就这么多吧,如果你有不同的答案欢迎留言~