- 创建方式
var a = new String('hello world');
var a = 'hello world';
2.方法
- 字符方法:
charAt() 以单字符串的形式返回给定位置的那个字符;
charCodeAt() 以单字符串的形式返回给定位置的那个字符编码;
fromCharCode() 方法接受一个或多个字符编码,然后将他们转换成一个字符串
例如:
var c = 'hello jingdong';
// charAt() 通过下标找元素
console.log(c.charAt(2));//l
console.log(c.charAt(4));//o
console.log(c.charAt(8));//n
// charCodeAt() 通过下标找字符编码
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));//从下标2开始到最后;
console.log(brr.slice(2,7));//下标为2 ,到7前一个结束
console.log(brr.slice(2,-4));//llo w
// substring() 有负数把负数转化为0 从大到小 0-3;
console.log(brr.substring(3,-5))//llo w
// substr() 下标 个数
console.log(brr.substr(1,4));// ello 下标为1 找4个
console.log(brr.substr(2,5));//llo w
console.log(brr.substr(3,-4));//''空字符串
- 字符串位置方法
// indexOf() 通过元素找下标 从前往后找
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
- 字符串 转数组 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