字符串
表示字符串方式:
"該號碼可註冊"
"13982291704"
""
"http://www.163.com"
'http://www.163.com'
比如要判斷字符的長度
str.length
"mircromajor".length;//11
用戶不能包含某些字符輸入
通過方法str.charAt(index);//index表示索引值
micromajor".charAt(0);//"m"
”
用戶輸入必須包含某些字符
通過str.indexOf(searchValue[,fromIndex])
"micro-major".indexOf("-");//返回這個字符所在的字符位置//5
"micro-major-web".indexOf("-")//5,匹配首先找到的位置
"micro-major".indexOf("major")//6,查找整個字符串時返回這個字符串首字母所在位置。
"micromajor".indexOf("-")//字符不存在的話,會返回-1,**常用應用場景**
輸入中不能含有數字
str.indexOf(“”);方法只能指定某些字符,但數字是一些集合,所以str.indexOf()方法不合理
方法:
str.search(regexp);//它的參數爲一個正則參數
"micromajor163".search(/[0-9]/);// /[0-9]/表示的集合,返回索引位置,爲出現的位置
"micromajor163".search(/[A-Z]/);//-1,沒有找到則返回-1;
替換字符串
str.replace(regexp | substr, newSubstr | function)
"micromajor163".replace("163","###");//"micromajor###"
"micromajor163".replace(/[0-9]/,"#");//"micromajor#63"
"micromajor163".replace(/[0-9]/g,"#");//"micromajor###",因爲正則表達式中爲/[0-9]/g
"micromajor163".replace(/[0-9]/g, "");//"micromajor",**將數字去除**
截取一部分字符串
方法一:
str.substring(indexA[,indexB])
indexA:初始索引位置
indexB:結束索引位置
"micromajor".substring(5,7) //"ma"
注意:索引值能取到在位置5的值,在7的位置之前停止。所以取"ma"
"micromajor".substring(5);//"major"
注意:只設置初始索引值時,會將後面的所有字符取到,所以爲major
方法二:
str.slice(beginSlice[,endSlice])
區別在於能用負值參數,表示倒數索引
"micromajor".slice(1,-1);//"icromajo", "r"的索引值是-1,但是不會取到索引爲-1的值
"micromajor".slice(5,7);//"ma"
"micromajor".slice(5);//"major"
方法三:
str.substr(star[,length])
"micromajor".substr(5,2); //"ma"
"micromajor".substr(5);//"major"
分割存儲
str.split([separator][,limit])
[separator]----是表示以這個符號作爲字符串的分割界限
分割後以數組的形式返回
"macro major".split(" "); // ["micro","major"]
"macro major".split(" ", 1);// ["micro"]
"macro2major".split(/[0-9]/);//["micro","major"]
字符串大小寫轉換
**轉爲小寫:**
str.toLowerCase()
"MicroMajor".toLowerCase(); //"micromajor"
轉爲大寫:
str.toUpperCase()
"MicroMajor".toUpperCase();//"MICROMAJOR"
轉字符串
String()
String(163);//"163"
String(null);//"null"