歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> JavaScript類型系統之String

JavaScript類型系統之String

日期:2017/3/1 9:19:42   编辑:Linux編程

前面的話

  string是由單引號或雙引號括起來的字符序列,且被限定在同種引號之間,即必須是成對單引號或雙引號。字符串的獨特在於它是唯一沒有固定大小的原始類型

  字符串中每個字符都有特定的位置,首字符從位置0開始,第二個字符在位置1,依次類推,這意味著字符串中的最後一個字符的位置一定是字符串的長度減1

特點

  JavaScript中的字符串是不可變的。字符串連接需要先創建一個新字符串,然後在新字符串中填充兩個需要拼接的字符串,最後再銷毀原來的字符串。這個過程在後台發生,也是在某些舊版本浏覽器(IE6)拼接字符串速度慢的原因,但後來已經解決了這個低效率問題。

var lang = "java";
lang = lang + "script";

轉義字符

  轉義字符也叫字符字面量

\0 空字節
\n 換行
\t 制表
\b 空格
\r 回車
\f 進紙
\\ 斜槓
\' 單引號
\" 雙引號
\xnn 以十六進制nn表示一個字符(n為0-f),如\x41表示'A'
\unnnn 以十六進制nnnn表示一個Unicode字符(n為0-f),如\u03a3表示希臘字符ε

  當字符串中包含引號,有三種解決方案

  [1]單引號中嵌入雙引號

  [2]雙引號中嵌入單引號

  [3]使用轉義符"\"

console.log('"test"');//"test"
console.log("'test'");//'test'
console.log('\'test\'');//'test'

繼承的方法

  String類型是與字符串對應的包裝類型,繼承了引用類型的通用方法

  valueOf()、toString()和toLocaleString():返回字符串表示

console.log("test".valueOf());//"test"
console.log("test".toString());//"test"
console.log("test".toLocaleString());//"test"

length屬性

  String類型的每個實例都有一個length屬性,表示字符的個數

  [注意]該屬性只可讀取,不可改變

var str = "test";
console.log(str.length);//4
str.length = 6;
console.log(str,str.length);//"test",4

String()方法

  String()方法的轉換規則是:

  [1]如果值有toString()方法,則調用該方法(沒有參數)並返回相應結果

  [2]null和undefined沒有toString()方法,則返回null和undefined

console.log(undefined.toString())//報錯
console.log(null.toString())//報錯
console.log(String(undefined));//'undefined'
console.log(String(null));//'null'
console.log(String(true),String(false));//'true' 'false'
console.log(String(10.1));//10.1
console.log(String({}));//[object Ojbect]

  [注意]要把某個值轉換為字符串,可以使用加號操作符把它與一個空字符串''加在一起

console.log(typeof (1 + ''),(1 + ''));//string '1'
console.log(typeof (undefined + ''),(undefined + ''));//string 'undefined'
console.log(typeof (null + ''),(null + ''));//string 'null'
console.log(typeof (true + ''),(true + ''));//string 'true'
console.log(typeof ({} + ''),({} + ''));//string '[object Object]'

訪問字符方法

  接收一個基於0的字符位置的參數,並以單字符字符串的形式返回

charAt():返回給定位置的字符

  [注意]當參數為空時,默認參數為0;當參數超出范圍時,則什麼都不輸出

var str = "hello";
console.log(str.charAt(1));//e
console.log(str.charAt(-1));//空
console.log(str.charAt(10));//空
console.log(str.charAt());//h

中括號加數字索引(ES5):返回給定位置的字符(IE7-不支持,輸出undefined)

  [注意]當參數超出范圍時,輸出undefined;當參數為空時,報錯

var str = "hello";
console.log(str[1]);//e
console.log(str[-1]);//undefined
console.log(str[10]);//undefined
console.log(str[]);//報錯

charCodeAt():返回給定位置的字符編碼,字符編碼為Number類型

[注意]當參數為空時,默認參數為0;當參數超出范圍時,則輸出NaN

var str = "hello";
console.log(str.charCodeAt(1));//101
console.log(str.charCodeAt(-1));//NaN
console.log(str.charCodeAt(10));//NaN
console.log(str.charCodeAt());//104

String.fromCharCode():把一個或多個編碼值轉成一個字符串(靜態方法)

[注意]參數范圍為ASCII表的范圍

var stringValue = 'hello';
console.log(stringValue.charAt(1));//'e'
console.log(stringValue.charCodeAt(1));//101
console.log(typeof stringValue.charCodeAt(1));//'number'
console.log(String.fromCharCode(104,101,108,108,111));//'hello'
console.log(String.fromCharCode(0x6211,0x662f,0x5c0f,0x706b,0x67f4));//'我是小火柴'
console.log(stringValue[1]);//'e'

字符串拼接

concat():可以接受任意多個參數,用於將一個或多個字符串拼接起來,返回拼接得到的新字符串

+:加號操作符在多數情況下比concat()更簡便

var stringValue = 'hello ';
console.log(stringValue.concat('world','!'));//'hello world!'
console.log(stringValue + 'world' + '!');//'hello world!'

創建字符串

  返回被操作字符串的一個子字符串,若無參數則返回原字符串。共substr、subtring和slice三種

substr(a,b):a->子字符串開始位置、b->子字符串長度(可選,默認到原字符串結束)

  設原字符串長度為len

  [1]當a>=len時,不輸出

  [2]當 a<0 且 |a|<len 時,從後往前數,輸出|a|個字符

  [3]當 a<0 且 |a|>= len 時,輸出從(0)到(b)的位置

  [4]當 b<0 時,b = 0

  [5]當 b>= 可提供字符數時,以最大字符數輸出

  [注意]IE8-在處理第一個參數為負值時存在問題,輸出原字符串

var stringValue = 'hello world';
console.log(stringValue.substr());//'hello world'
console.log(stringValue.substr(2));//'llo world'
console.log(stringValue.substr(20));//空
console.log(stringValue.substr(-2,3));//'ld'
console.log(stringValue.substr(-2,20));//'ld'
console.log(stringValue.substr(-20,2));//'he'
console.log(stringValue.substr(-20,-2));//空
console.log(stringValue.substr(2,5));//llo w

substring(a,b):a->子字符串開始位置、b->子字符串結束後一位的位置(可選,默認為原字符串長度)

  設原字符串長度為len

  [1]當a<0時,a=0;當b<0時,b=0

  [2]當a>b>0時,substring(b,a)

  [3]當a>=len時,無輸出

  [4]當b>=len時,以最大字符數輸出

var stringValue = 'hello world';
console.log(stringValue.substring());//'hello world'
console.log(stringValue.substring(2));//'llo world'
console.log(stringValue.substring(20));//空
console.log(stringValue.substring(-2,2));//'he'
console.log(stringValue.substring(-2,20));//'hello world'
console.log(stringValue.substring(3,2));//'l'
console.log(stringValue.substring(-20,2));//'he'
console.log(stringValue.substring(-20,-2));//空

slice(a,b):a->子字符串開始位置,b->子字符串結束後一位的位置(可選,默認為原字符串長度)

  設原字符串長度為len

  [1]當 a>=len 時,不輸出

  [2]當 a<0 且 |a|<len 時,a = len - |a|

  [3]當 a<0 且 |a|>= len 時,輸出從(0)到(b)的位置

  [4]當 b>=len 時,相當於沒有b

  [5]當 b<0 且 |b|<len 時,b = len - |b|

  [6]當 b<0 且 |b|>=len 時,不輸出

  [7]當 a>b>0時,不輸出

var stringValue = 'hello world';
console.log(stringValue.slice());//'hello world'
console.log(stringValue.slice(2));//'llo world'
console.log(stringValue.slice(2,-5));//'ll0'
console.log(stringValue.slice(2,-20));//空
console.log(stringValue.slice(20));//空
console.log(stringValue.slice(-2,2));//空
console.log(stringValue.slice(-2,-20));//空
console.log(stringValue.slice(-2,20));//'ld'
console.log(stringValue.slice(-20,2));//'he'
console.log(stringValue.slice(-20,-2));//'hello wor'

字符串位置

  有兩個從字符串中查找子字符串的方法indexOf()和lastIndexOf()。這兩個方法都接受兩個參數:要查找的子字符串和表示查找起點位置的索引(可選)。返回第一個滿足條件的子字符串在字符串中的位置,若沒有找到則返回-1(位置方法不會影響原字符串)

  [注意]返回值是Number類型

indexOf():從左到右搜索

lastIndexOf():從右到左搜索

var string = 'hello world world';
console.log(string.indexOf('ld',10));//15
console.log(string.lastIndexOf('ld',10));//9

[tips]查找出字符串所有符合條件的子字符串

function allIndexOf(str,value){
var result = [];
var pos = str.indexOf(value);
while(pos > -1){
result.push(pos);
pos = str.indexOf(value,pos+value.length);
}
return result;
}
console.log(allIndexOf('helllhelllhelll','ll'));//[2,7,12]

大小寫轉換

toUpperCase():全部轉換成大寫

toLowerCase():全部轉換成小寫

toLocaleUpperCase():全部轉換成大寫(針對地區)

toLocaleLowerCase():全部轉換成小寫(針對地區)

  [注意]在不知道自己的代碼將在哪個語言環境中運行的情況下,使用針對地區的方法更穩妥

var string = 'Hello World';
console.log(string.toLowerCase());//hello world
console.log(string.toLocaleLowerCase());//hello world
console.log(string.toUpperCase());//HELLO WORLD
console.log(string.toLocaleUpperCase());//HELLO WORLD

  [注意]大小寫轉換方法可以連續使用

console.log((string.toUpperCase()).toLowerCase());//hello world

字符串比較

localeCompare():用於比較兩個字符串,如果字符串在字母表中應該排在字符串參數之前,則返回一個負數(大多數情況下為-1);如果字符串等於字符串參數,則返回0;如果在之後,則返回一個正數(大多數情況下為1)

  [注意]在ASCII表中,大寫字母排在小寫字母前面

var stringValue = 'yellow';
console.log(stringValue.localeCompare('brick'));//1 'y'> 'b'
console.log(stringValue.localeCompare('yellow'));//0 'yellow' == 'yellow'
console.log(stringValue.localeCompare('zoo'));//-1 'yellow' < 'zoo'

模式匹配

  String類型定義了幾個用於字符串匹配模式的方法。模式匹配涉及到正則表達式的內容,詳細信息移步至此

match()

  只接受一個參數,正則或字符串,把匹配的內容保存到一個數組中返回

  [注意]加上全局標記時,match()方法返回值中沒有index和input屬性

[1]不加/g

var string = 'cat,bat,sat,fat';
var pattern = /.at/;
var matches = string.match(pattern);
console.log(matches,matches.index,matches.input);//['cat'] 0 'cat,bat,sat,fat'

[2]加/g

var string = 'cat,bat,sat,fat';
var pattern = /.at/g;
var matches = string.match(pattern);
console.log(matches,matches.index,matches.input);//['cat','bat','sat','fat'] undefined undefined

[3]字符串

var string = 'cat,bat,sat,fat';
var pattern = 'at';
var matches = string.match(pattern);
console.log(matches,matches.index,matches.input);//['at'] 1 'cat,bat,sat,fat'

search()

  只接受一個參數,正則或字符串,返回匹配的內容在字符串中首次出現的位置,類似於不能設置起始位置的indexOf,找不到返回-1

[1]正則(加/g和不加/g效果一樣)

var string = 'cat,bat,sat,fat';
var pattern = /.at/;
var pos = string.search(pattern);
console.log(pos);//0

[2]字符串

var string = 'cat,bat,sat,fat';
var pattern = 'at';
var pos = string.search(pattern);
console.log(pos);//1

[tips]找出匹配的所有位置

function fnAllSearch(str,pattern){
var pos = str.search(pattern);
var length = str.match(pattern)[0].length;
var index = pos+length;
var result = [];
var last = index;
result.push(pos);
while(true){
str = str.substr(index);
pos = str.search(pattern);
if(pos === -1){
break;
}
length = str.match(pattern)[0].length;
index = pos+length;
result.push(last+pos);
last += index;
}
return result;
}
console.log(fnAllSearch('cat23fbat246565sa3dftf44at',/\d+/));//[3,9,17,22]

replace()

  該方法接收兩個參數:第一個為正則表達式或字符串(待查找的內容)、第二個為字符串或函數(替換的內容)

[1]字符串替換

var string = 'cat,bat,sat,fat';
var result = string.replace('at','ond');
console.log(result);//'cond,bat,sat,fat'

[2]正則無/g替換

var string = 'cat,bat,sat,fat';
var result = string.replace(/at/,'ond');
console.log(result);//'cond,bat,sat,fat'

[3]正則有/g替換

var string = 'cat,bat,sat,fat';
var result = string.replace(/at/g,'ond');
console.log(result);//'cond,bond,sond,fond'

[4]函數替換

  在只有一個匹配項(即與模式匹配的字符串的情況下,會向這個函數傳遞3個參數:模式的匹配項、模式匹配項在字符串中的位置、原始字符串。在正則表達式定義了多個捕獲組的情況下,傳遞給函數的參數依次是模式的匹配項、第一個捕獲組的匹配項、第二個捕獲組的匹配項……第N個捕獲組的匹配項,但最後兩個參數仍然分別是模式的匹配項在字符串中的位置和原始字符串,這個函數返回一個字符串

var string = 'cat,bat,sat,fat';
var index = 0;
var result = string.replace(/at/g,function(match,pos,originalText){
index++;
if( index== 2){
return 'wow';
}else{
return '0';
}
});
console.log(result);//'c0,bwow,s0,f0'

[tips]防止跨站腳本攻擊xss(css)

function htmlEscape(text){
return text.replace(/[<>"&]/g,function(match,pos,originalText){
switch(match){
case '<':
return '&lt;';
case '>':
return '&gt;';
case '&':
return '&amp;';
case '\"':
return '&quot;';
}
});
}
console.log(htmlEscape('<p class=\"greeting\">Hello world!</p>'));
//&lt;p class=&quot; greeting&quot;&gt;Hello world!&lt;/p&gt;
console.log(htmlEscape('<p class="greeting">Hello world!</p>'));
//同上

split()

  這個方法可以基於指定的分隔符將一個字符串分割成多個字符串,並將結果放在一個數組中,分隔符可以是字符串,也可以是一個RegExp。該方法可以接受第二個參數(可選)用於指定數組的大小,如果第二個參數為0-array.length范圍內的值時按照指定參數輸出,其他情況將所有結果都輸出

  [注意]IE8-對split()中的正則表達式,會忽略捕獲組

[tips]如果是split(''),則原來的數組會一個字符字符分割後傳出來

var colorText = 'red,blue,green,yellow';
console.log(colorText.split(''));//["r", "e", "d", ",", "b", "l", "u", "e", ",", "g", "r", "e", "e", "n", ",", "y", "e", "l", "l", "o", "w"]
console.log(colorText.split(','));//["red", "blue", "green", "yellow"]
console.log(colorText.split(',',2));//["red", "blue"]
console.log(colorText.split(/\,/));//["red", "blue", "green", "yellow"]
console.log(colorText.split(/e/));//["r", "d,blu", ",gr", "", "n,y", "llow"]
console.log(colorText.split(/[^\,]+/));//將除去逗號以外的字符串變為分隔符["", ",", ",", ",", ""],IE8-會識別為[",",",",","]

trim()(ECMAScript5)

  返回刪除前置及後綴空格的字符串副本

var string = ' hello world ';
console.log(string.trim());//'hello world';

[tips1]可以用trim()來判斷輸入的字符是否為空

if(usename.trim().length){
alert('correct');
}else{
alert('error');
}

[tips2]用正則模擬trim()

function fnTrim(str){
return str.replace(/^\s+|\s+$/,'')
}
console.log(fnTrim(' hello world '));//'hello world'

Copyright © Linux教程網 All Rights Reserved