1.用String構(gòu)造函數(shù)創(chuàng)建。
var str= new String("Hello World");
var str = String("Hello World");
var str = "Hello World";
2.字符方法
charAt() 以單字符串的形式返回給定位置的那個字符
charCodeAt() 以單字符串的形式返回給定位置的那個字符編碼
var str = "Hello world";
console.log(str.charAt(1)); //e
console.log(str.charCodeAt(1)); //101 “e”的字符編碼
fromCharCode() 方法
接受一個或多個字符編碼,然后將他們轉(zhuǎn)換成一個字符串。
console.log(String.fromCharCode(104,101,108,108,111)); //hello
3.字符串拼接
concat() 用于將一個或多個字符串拼接起來,返回拼接得到的新字符串。
var str = "hello ";
var newStr = str.concat("world","!");
console.log(newStr); //"hello world!"
console.log(str); //不改變原字符串
- 字符串位置方法
indexof()
lastIndexof()
var str = "hello world";
console.log(str.indexof("o")); //4
console.log(str.lastIndexof("o")); //7
console.log(str.indexof("o",6)); //7
console.log(str.lastIndexof("o",6)); //4
如果檢測不到返回-1
6.字符串大小寫轉(zhuǎn)換方法
toLowerCase() 轉(zhuǎn)小寫
toLocaleLowerCase() 根據(jù)特定地區(qū)的語言轉(zhuǎn)小寫
toUpperCase() 轉(zhuǎn)大寫
toLocaleUpperCase() 根據(jù)特定地區(qū)轉(zhuǎn)大寫
var str = "hello world";
console.log(str.toUpperCase()); //"HELLO WORLD"
console.log(str.toLocaleUpperCase()); //"HELLO WORLD"
console.log(str.toLowerCase()); //"hello world"
console.log(str.toLocaleLowerCase()); //"hello world"
- replace() 為了簡化替換子字符串的操作。
該方法接受兩個參數(shù):1)可以是一個RegExp對象或者一個字符串 2)可以是一個字符串或者函數(shù)
var text = "cat,bat,sat,fat";
var result = text.replace("at","ond");
console.log(result); //cond,bat,sat,fat
result = text.replace(/at/g,"ond");
console.log(result); //cond,bond,sond,fond
- split() 以指定的分隔符將一個字符串分割成多個子字符串,并將結(jié)果放在一個數(shù)組
var colors = "red,blue,green,yellow";
var colors1 = colors.split(",");
console.log(colors1)//["red", "blue", "green", "yellow"]
var s = colors.split("e");
console.log(s); // ["r","d,blu",",gr","","n,y","llow"]