- 創(chuàng)建方式
var a = new String('hello world');
var a = 'hello world';
2.方法
- 字符方法:
charAt() 以單字符串的形式返回給定位置的那個(gè)字符;
charCodeAt() 以單字符串的形式返回給定位置的那個(gè)字符編碼;
fromCharCode() 方法接受一個(gè)或多個(gè)字符編碼,然后將他們轉(zhuǎn)換成一個(gè)字符串
例如:
var c = 'hello jingdong';
// charAt() 通過下標(biāo)找元素
console.log(c.charAt(2));//l
console.log(c.charAt(4));//o
console.log(c.charAt(8));//n
// charCodeAt() 通過下標(biāo)找字符編碼
console.log(c.charCodeAt(4));//111
console.log(c.charCodeAt(8));//110
//String.fromCharCode() 通過編碼找字符
console.log(String.fromCharCode(111,110));//on
- 字符串操作方法
例子:
var arr = 'hello';
//concat() 字符串拼接起來, 返回拼接得到的新字符串
var brr = arr.concat('world','!')
console.log(brr);//hello worla !
- slice()、substr() 和 substring()。
var brr = 'hello world';
console.log(brr.slice(2));//從下標(biāo)2開始到最后;
console.log(brr.slice(2,7));//下標(biāo)為2 ,到7前一個(gè)結(jié)束
console.log(brr.slice(2,-4));//llo w
// substring() 有負(fù)數(shù)把負(fù)數(shù)轉(zhuǎn)化為0 從大到小 0-3;
console.log(brr.substring(3,-5))//llo w
// substr() 下標(biāo) 個(gè)數(shù)
console.log(brr.substr(1,4));// ello 下標(biāo)為1 找4個(gè)
console.log(brr.substr(2,5));//llo w
console.log(brr.substr(3,-4));//''空字符串
- 字符串位置方法
// indexOf() 通過元素找下標(biāo) 從前往后找
var crr = 'abcdefdbhi';
console.log(crr.indexOf('b'));//1
console.log(crr.indexOf('b' ,2));//7
console.log(crr.indexOf('b' ,-5));//1
//lastIndexOf() 從后往前找
console.log(crr.lastIndexOf('d',3));//3
console.log(crr.lastIndexOf('d',5));//3
- 字符串 轉(zhuǎn)數(shù)組 split()
//
var str = 'hello';
console.log(str.split(''));//["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"]
- trim() 去掉前面和后面的空格.
var drr = ' love ';
console.log(drr.trim());//love