String类型详解

1.简介:

对于字符串,在现实生活中,字符串无处不在。包括我们说的每一句话,例如,baidu.com,甚至写的文字也算是字符串的一种。在计算机的世界中,对于不同的编程语言,前端和后端的数据交互,字符串都是一种通用的传输,就好像json。

2.创建:

对象形式创建:

var str = new String('baidu.com');

字面量形式创建:

var str = 'helloWorld';

 3.检测:

使用typeof检测:

var str1 = 'baidcu.com';
var str2 = new String('helloWorld');
console.log(typeof str1,typeof str2);//string Object
注:我们知道,只要对象才有方法,通过字面量创建的字符串不是一个对象,当调用其方法时,系统会自动转化为Object类型,所以才可以使用字符串的方法。

4.字符串提供的API(我们可以自己猜一下可能会有的API,对字符串我们可能需要大小写转换,去空白,截断,查找....):

1)通过length属性获取字符串长度:

var str = 'helloWorld';
console.log(str.length); //10

2)大小写转换:

console.log('hello'.toUpperCase()); //HELLO
console.log('HELLO'.toLowerCase()); //hello

3)移除空格(在用户输入密码时,空格应该移除):

console.log('   passwd  '.length);               //11
console.log('   passwd  '.trim().length);       //6     
console.log('   passwd  '.trimLeft().length);  //8
console.log('   passwd  '.trimRight().length); //9

4)获取单个字符串:

//通过charAt()函数:
console.log('hello'.charAt(4));  //o
//通过数字索引:
console.log('hello'[3]);

5)查找字符串:

//通过indexOf()从开始查找,找不到返回-1(以为索引不可能为负数):
//lastIndexOf()从后面向前找
console.log('hello'.indexOf('he'));  //0
console.log('hello'.indexOf('k'));    //-1
console.log('hello'.indexOf('he',1));//-1

//search() 方法用于检索字符串中指定的子字符串,也可以使用正则表达式搜索
console.log('baidu.com'.search('com'));  //6
console.log('baidu.com'.search(/\.com/i)); //5

//includes 字符串中是否包含指定的值,第二个参数指查找开始位置,返回的是布尔值:
console.log('baidu.com'.includes('com'));  //true

6)截断字符串(对于某些字符串,我们可能只需要重要的部分,因此需要截断):

//使用slice(),substr,subString()都可以截断字符串
//第一个参数都是从什么位置开始
//slice(),subString()为结束位置,substr()为需要截取的数量
var params = 'user:admin';
console.log(params.slice(5,10));     //admin
console.log(params.substr(5,2));    //ad
console.log(params.substring(5,8));//adm        

7)替换字符串

//使用replace()函数可以替换字符串,不改变原字符串
var str = 'baidu.com';
var str1 = str.replace('baidu','google')
console.log(str,str1); //baidu.com google.com

8)重复生成:

//使用repeat()重复生成字符
var phoneNum = '18165082368';
function fun(phoneNum) {
  return phoneNum.slice(0,-3) + '*'.repeat(3);
}
console.log(fun(phoneNum)); //18165082***

9)类型转换(重要):

转为字符串:

//1.隐式转换,通过拼串:
var str = 99 + '';
console.log(typeof str);

//2.调用构造函数String():
var str = 99;
var b = String(str);
console.log(typeof str,typeof b); //Number,String

//3.js中大部分类型都是对象,可以使用类方法 toString转化为字符串
var str = 99;
var b = str.toString();
console.log(typeof str,typeof b); //Number,String

字符串转其他:

//split()方法,将一个字符串转为数组
var str = '1,2,3';
var a = str.split(',');
console.log(typeof str,typeof a); //String Object

//使用点语法
var str = '123';
var a = [...str];
console.log(a,str); //['1','2','3']  123
posted @ 2021-04-23 12:26  星空的轨迹  阅读(488)  评论(0编辑  收藏  举报