创建方式
String类型是字符串的对象包装类型,可以使用String构造函数创建。
例:
var strObj = new String("Hello World");
`
方法
继承的toLocaleString()、toString和valueof()方法,都返回对象所表示的基本字符串值。
String类型的每一个实例都有一个length属性,表示字符串中包含了多少了字符。
例:
var str = "hello world";
console.log(str.length); //11
`
字符方法
charAt() 以单字符串的形式返回给定位置的那个字符
var a= 'Hello world '
console.log(a.charAt(1)) //e
charCodeAt() 以单字符串的形式返回给定位置的那个字符编码
var a= 'Hello world '
console.log(a.charCodeAt(1)) //101 “e”的字符编码
这两个方法都接收一个参数,即基于0的字符位置(下标)。
`
字符串操作方法
concat 拼接
var arr ='hello';
var brr= arr.concat(' world','!')
console.log(brr) // hello world!
console.log(arr) // hello
slice()、 substr() 和 substring()
var arr = 'hello world'
// slice (下标为 ,到 前一个结束 )
console.log(arr.slice(1)) // 从下标1开始到最后; ello world!
console.log(arr.slice(1,3)) // el
console.log(arr.slice(1,-4)) // ello w
// substr() 下标 个数
console.log(arr.substr(1,4)) // ello
console.log(arr.substr(3,6)) // lo wro
console.log(brr.substr(3,-4));// '' 空字符串
// substring() 有负数把负数转化为0 从大到小;
console.log(arr.substring(3,5)) // lo 下标为3 ,到5前一个结束
console.log(arr.substring(-4)) // hello wold
console.log(arr.substring(-3,4)) // hell
console.log(arr.substring(5,-4)) // hello
字符串位置方法 (通过元素找下标)
// indexOf() 通过元素找下标 从前往后找
var arr = '123238495782';
console.log(arr.indexOf('8'));//5
console.log(arr.indexOf('2' ,2));//3
console.log(arr.indexOf('2' ,-5));//1
// lastIndexOf() 通过元素找下标 从后往前找
console.log(arr.lastIndexOf('2', 3)); //3
console.log(arr.lastIndexOf('8', 5)); //5
字符串 转数组 split()
var arr = "hello";
console.log(drr.trim('')); // ['h','e', 'l", "l", "o"]
var a = "one,two,three,four";
console.log(a)
var b = a.split(",");
console.log(b)
var b = a.split(",", 3); //长度3
console.log(b); // ["one", "two", "three"]
var see = a.split('e');
console.log(see); //["on", ",two,thr", "", ",four"]