1. 字符串拼接
2. 查找字符串
3. 字符串截取
4. 字符串分割爲數組
5. 大小寫轉換
6. 字符串替換
7. 正則表達式匹配
8. 一些擴展正則表達式
concat
將2個或多個字符串拼接起來數組
var a = "hello"; var b = ",world"; var c = a.concat(b); // c = "hello,world"
indexOf
返回字符串中一個子串第一處出現的索引(從左到右搜索)。若是沒有匹配項,返回-1
。code
var a = "helolo"; var index1 = a.indexOf("l"); //index1 = 2 var index2 = a.indexOf("l",3);//表示從第4位開始查找「l」第一次出現的位置 //index2 = 4
lastIndexOf
返回字符串中一個子串第一處出現的索引(從左到右搜索)。若是沒有匹配項,返回-1
。索引
var a = "helolo"; var index1 = a.lastIndexOf("l"); //index1 = 4 var index2 = a.lastIndexOf("l",2); //index2 = 2
charAt
用來獲取指定位置的字符ip
var a = "hello"; var get_char = a.charAt(0); //get_char = "h"
substring
返回字符串的一個子串,傳入參數是起始位置和結束位置。字符串
var a = "hello"; var sub_string1 = a.substring(1); //sub_string1 = "ello" var sub_string2 = a.substring(1,4); //sub_string2 = "ell"
substr
返回字符串的一個子串,傳入參數是起始位置和長度。get
var a = "hello"; var sub_string1 = a.substr(1); //sub_string1 = "ello" var sub_string2 = a.substr(1,2); //sub_string2 = "el"
split
經過將字符串劃分紅子串,將一個字符串作成一個字符串數組。string
var a = "hello"; var arr1 = a.split(""); //arr1 = [h,e,l,l,o]
var a = "Hello"; var lower_string = a.toLowerCase(); //lower_string = "hello"
var a = "Hello"; var upper_string = a.toUpperCase(); //upper_string = "HELLO"
replace
p.s.replace
是嚴格大小寫的it
var a = "hello world"; var result = a.replace(/world/,"otto"); //result = "hello otto";
執行一次全局替換,每當Microsoft
被找到,它就被替換爲World
io
var str="Welcome to Microsoft! " str=str + "We are proud to announce that Microsoft has " str=str + "one of the largest Web Developers sites in the world." var result = str.replace(/Microsoft/g,"World"); //result = "Welcome to World! We are proud to announce that World has one of the largest Web Developers sites in the world.";
var name = 'aaa bbb ccc'; var result = name.replace(/\b\w+\b/g, function (word) { return word.substring(0, 1).toUpperCase() + word.substring(1); } ); //result = "Aaa Bbb Ccc";
match
檢查一個字符串匹配一個正則表達式內容,若是不匹配則返回 null。
var a = "hello"; var b = ",world"; var re = new RegExp(/^\w+$/); var is_alpha1 = a.match(re); //is_alpha1 = "hello" var is_alpha2 = b.match(re); //is_alpha2 = null
function getFileName(originalname) { var indexNum = originalname.lastIndexOf('.'); if (indexNum != -1) { var fileName = originalname.substr(0, indexNum); return fileName; } else { return "NULL"; } } var result = getFileName("233.333-333.text"); //result = "233.333-333";
function isIP(str) { var reSpaceCheck = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/; if (reSpaceCheck.test(str)) { str.match(reSpaceCheck); if (RegExp.$1 <= 255 && RegExp.$1 >= 0 && RegExp.$2 <= 255 && RegExp.$2 >= 0 && RegExp.$3 <= 255 && RegExp.$3 >= 0 && RegExp.$4 <= 255 && RegExp.$4 >= 0) { return true; } else { return false; } } else { return false; } }