JavaScript內置對象之String

字符串的介紹

js字符串的概念
字符串就是一串字符,由雙(單)引號括起來。
字符串是 JavaScript 的一種數據類型。
創建字符串
基本類型(字面量)

var str1 ="阿夕"//基本類型字符串
console.log(str1)// 阿夕
console.log(typeof str1)// string
console.log(str1.length)//2

引用類型(構造函數)

var str2 = new String("阿夕");//引用類型字符串
console.log(str2)//是一個可以展開的string 點擊之後會顯示長度原型爲string等
console.log(typeof str2)//object
console.log(str2.length)//2

// 構造函數:字符對象,通過new執行字符構造函數得到,雖然長得是對象的外表,但是他內心還是字符串(作爲一個正常的字符來使用)

模板字符串

var str3 = `bb ${a}
				b`;//es6 模板字符串  裏面可以寫變量
console.log(str3)//bb 1						b
console.log(typeof str3)//string
console.log(str3.length)//12

字符串的常用方法

str4.charAt(3)

var str4 = "hello word"
console.log(str4.charAt(3));//l 顯示字符串中下標爲3的字符

str.charCodeAt(3) 獲取下標爲3的字符的編碼(ASCII碼)

var str5 = "hello word"
console.log(str5.charCodeAt(3));//108

str.concat(); 連接字符串

var str6 = "hello "
console.log(str6.concat("word"))//hello word

str.indexOf(“hello”);
查找字符串第一次出現的位置, 如果沒找到則返回-1

var str7 = "hello word";
var subStr = "hello";
console.log(str7.indexOf(subStr))//0

str.lastIndexOf(“abc”); 查找字符串最後一次出現的位置, 如果沒找到則返回-1
indexOf和lastIndexOf():區別是如果第一個參數爲負數,數組是從後往前找,字符串當做0處理。

var str8 = "hello word";
console.log(str8.lastIndexOf("d"))//9
var str = "hello world";
console.log(str8.indexOf("l",10));//-1 找不到返回-1

str.search(); 正則匹配 (返回第一次出現的位置)

 var str9 = "hello word"; 
console.log(str9.search(/llo/gi))//2

str.replace(); 替換字符串;這裏的替換隻能執行一次,不能夠進行全局匹配

var str10 = "how are Are are you!"; 
console.log(str10.replace("are", "old are"));//how old are Are are you!

str.toLowerCase(); 把字符串轉換成小寫

var str11 = "HELLO WORD";
console.log(str11.toLowerCase())//hello word

str.toUpperCase(); 把字符串轉換成大寫

var str12 = "hello word";
console.log(str11.toUpperCase())//HELLO WORD

split():根據分隔符、將字符串拆分成數組。

var str13 = "hello word";
    console.log( str13.split("-"));//["hello word"]

substring():用來截取字符串的內容


     var str14 = "hello world";
     console.log(str14.substring(2,7));//llo w

substr(start, length):用來截取字符串的內容

  var str15 = "hello world";
 console.log(str15.substr(2,7));  //llo wor  

slice(2,7);已第一個參數爲開頭查找到第二個參數 但不包括第二個參數

var str16 = "hello world";
  console.log(str16.slice(2,7));//llo w

trim()去收尾空格;trimLeft()去左空格;trimRight()去右空格

var str17 =' hello world ';
var res =  str4.trim();
console.log(str4.length)//13
console.log(res.length)//11
console.log(res)//hello world
console.log(str17.trimLeft())//hello world 
console.log(str17.trimRight())// hello world

replace();字符替換;屏蔽髒話;

var str18 = 'aaa';
console.log(str18.replace('a','b'))//baa

新人初來,有很多欠缺需要大家多多指教,逆疫而戰大家加油

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章