標籤:需要 console case 選項 長度 cas 處理 截取字串 art
string對象屬性:
1、length
擷取字串的長度,需要注意的是,js中中文每個漢字也只代表一個字元。
var myName="xulinjun";console.log(myName.length); // 8
string對象方法:
1、charAt()
stringObject.charAt(index)
可以用來擷取指定位置的字串,index為字串索引值,從0開始到string.length-1,若不在此範圍,則返回一個Null 字元串。
var a="hello world~";console.log(a.charAt(4)); //o
2、charCodeAt()
stringObject.charCodeAt(index)
返回指定位置字元的Unicode編碼,與charAt()類似,index為索引值,區別是前者返回指定位置的字元的編碼,而後者返回的是字元子串。
var str = ‘abcde‘;console.log(str.charCodeAt(0)); //97
3、indexOf()
stringObject.slice(start[,end])
此方法用來檢索指定字元在字串中首次出現的位置,他可以接受兩個參數,searchvalue表示要尋找的子字串,fromindex表示尋找的開始位置,省略的話則從開始位置進行檢索。
var a="hello world~";console.log(a.indexOf("o")); //4console.log(a.indexOf("o",5)) //7console.log(a.indexOf("lo")); //3
4、slice();
stringObject.slice(start[,end])
就是截取字串中的某一段,start就是開始截取的位置索引,從0開始,如果start為負,將他作為length+start處理,length為字串長度。end是結束截取的位置索引,但截取的字串中不包括end位置那一個字元,從0開始,如果end為負,將他作為length+end處理。
此處,開始位置必須填寫,結束位置不一定要寫,不寫的話表示截取到末尾。
var a="123456";alert(a.slice(2)); //3456alert(a.slice(-2)) //56alert(a.slice(2,4)); // 34
5、substring()
stringObject.substring(start,end)
返回字串中指定位置的子字串,start是起始位置,end為結束位置,都是從0開始,substring()方法總是以start和end中較小的一個計為起始位置,較小的一個為結束位置,如果他們存在於NaN或負數,替換為0。
var a="123456";alert(a.substring(2,5)); //345alert(a.substring(1,6)); //23456
6、substr()
stringObject.substr(start[,length])
返回一個由指定位置開始的指定長度的字串,start為起始位置,length為長度,但不是必須,如果沒有,截取到末尾。
var a="123456";alert(a.substr(3,2)); //45alert(a.substr(3)); //456
7、indexOf()
stringObject.indexOf(substr[,startIndex])
返回string對象內第一次出現子字串位置,如果沒有找到指定子字串,返回-1,substr為指定子字串, startIndex該整數值表示從哪開始找,如果省略,則在開始處找(0)。
var a="ABCDEFG";alert(a.indexOf("EF",1)) //4alert(a.indexOf("C")); //2alert(a.inenxOf("Z")) //-1
8、lastIndexOf()
stringObject.lastIndexOf(substr[,startindex])
返回string對象中指定字串最後出現的位置,如果沒有匹配到,返回-1,substr為指定子字串,startindex該整數值指出在String對象內進行尋找的開始索引位置。如果省略,則尋找從字串的末尾開始。
var a="ABCDEFGB";alert(a.lastIndexOf("B")); //7
9、concat()
str.concat([string1[,string2...]])
返回字串,該字串包含了兩個或多個字串的拼接。
var a="123", b="456", c="789";console.log(a.concat(b,c)); //123456789
10、split()
stringObject.split([separator[,limit]])
將一個字串分割成子字串,然後將結果作為字串數組返回。 separator字串或 Regex 對象,它標識了分隔字串時使用的是一個還是多個字元。如果忽略該選項,返回包含整個字串的單一元素數組。
limit該值用來限制返回數組中的元素個數。
var a="AA-BB-CC";console.log(a.split("-")); //["AA", "BB", "CC"]console.log(a.split("-",2)); //["AA", "BB"]
11、toLowerCase()
返回一個字串,該字串中的大寫字母都被轉化為小寫。
var a="今天天氣很NICE";console.log(a.toLowerCase()); //今天天氣很nice
12、toUpperCase()
返回一個字串,該字串中的所有小寫字母都被轉化為大寫字母。
var a="今天天氣很nice";console.log(a.toUpperCase()); //今天天氣很NICE
javascript中字串常規操作