js 字符串String

創(chuàng)建方式

String類型是字符串的對象包裝類型,可以使用String構(gòu)造函數(shù)創(chuàng)建。

var str = new String('hello world')
var str = String('hello world')
var str = 'hello world'
字符方法

charAt() 以單字符串的形式返回給定位置的那個字符
charCodeAt() 以單字符串的形式返回給定位置的那個字符編碼
這兩個方法都接收一個參數(shù),即基于0的字符位置(下標(biāo))。

  var str = new String('hello world');
  console.log(str.charAt(3));//l  找下標(biāo)為3的元素
  console.log(str.charCodeAt(4));//'111'找下標(biāo)為4的元素的字符編碼
fromCharCode() 方法。

接受一個或多個字符編碼,然后將他們轉(zhuǎn)換成一個字符串

  console.log(String.fromCharCode(104,101,108,108,111)); //hello

字符串操作方法

concat

用于將一個或多個字符串拼接起來,返回拼接得到的新字符串

  var str = 'hello ';
  var newstr = str.concat('world','!');
  console.log(newstr);//返回拼接后的值
  console.log(str);//不改變原字符串

*** ES還提供了三個基于子字符串創(chuàng)建新字符串的方法:
slice(start,end)
substring(start,end)
substr(index,howmany)

  var str = 'hello world';
  console.log(str.slice(3));//截取下標(biāo)為3的后面的元素
  console.log(str.substring(3));//同上 lo world
  console.log(str.substr(3));//同上
  console.log(str.slice(3,7));//lo w  截取下標(biāo)3-7之間的元素
  console.log(str.substring(3,7));//lo w
  console.log(str.substr(3,7));//lo worl 截取下標(biāo)3開始后面的7個元素

在傳遞給這些方法的參數(shù)是負(fù)數(shù)的情況時,他們的行為就不相同了。

var str = "hello world";
console.log(str.slice(-3)); //"rld"
// console.log(str.substring(-3);//"hello world" 此方法的參數(shù)是負(fù)數(shù)都轉(zhuǎn)換為0
console.log(str.substr(-3)); //"rld"
console.log(str.slice(3,-4)); //"lo w"
console.log(str.substring(3,-4)); //"hel" 此方法會將較小的數(shù)作為開始位置
console.log(str.substr(3,-4)); //""(空字符串)

字符串位置方法
    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
trim()方法 此方法會創(chuàng)建一個字符串副本,刪除前置以及后綴的所有空格,然后返回結(jié)果。
var str = "  hello world   ";
var newStr = str.trim();
console.log(newStr);  //"hello world"
console.log(str);     //"  hello world   "
字符串大小寫轉(zhuǎn)換方法

toLowerCase() 轉(zhuǎn)小寫
toLocaleLowerCase() 根據(jù)特定地區(qū)的語言轉(zhuǎn)小寫
toUpperCase() 轉(zhuǎn)大寫
toLocaleUpperCase() 根據(jù)特定地區(qū)轉(zhuǎn)大寫

replace() 為了簡化替換子字符串的操作。
split() 以指定的分隔符將一個字符串分割成多個子字符串,并將結(jié)果放在一個數(shù)組
  var colors = "red,blue,green,yellow";
  var Es = colors.split("e");
  console.log(Es);  // ["r","d,blu",",gr","","n,y","llow"]
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容