1. stringObject.charAt()
作用:返回字符串的下標
var str="這是一串字符串"; console.log(str.charAt(0))//這
2. stringObject.charCodeAt()
作用: 方法可返回指定位置的字符的 Unicode 編碼
var str="這是一串字符串"; console.log(str.charCodeAt(0)) //這=>36825
3.String.fromCharCode()
作用:通過Unicode 編碼返回對應的字符
console.log(String.fromCharCode(36825,26159))//這是
例題:查找字符串是不是數字
<body>
<input type="text" />
<input type="button" value="檢測" />
<script>
var aInp = document.getElementsByTagName('input');
aInp[1].onclick = function () {
var val = aInp[0].value;
if ( detectNum(val) ) {
alert( '恭喜,'+ val +'全是數字' );
} else {
alert('輸入有誤');
}
};
function detectNum ( str ) {
var n = 0;
for ( var i=0; i<str.length; i++ ) {
n = str.charCodeAt(i);
if ( n<48 || n>57 )return false;
}
return true;
}
</script>
</body>
4. stringObject.indexOf()
作用:方法可返回某個指定的字符串值在字符串中首次出現的位置。
參數:str.indexOf(查找值,開始查找下標),如果要檢索的字符串值沒有出現,則該方法返回 -1。
例題:返回查找對應字符出現的下標
<script>
var str = 'xsxsxscdecdcdxsxsxs';
var num = 0;
var s = 'xs';
var arr = [];
for (; str.indexOf(s, num) != -1;) {
num = str.indexOf(s, num) + s.length
arr.push(num)
}
console.log(arr)
</script>
5. stringObject.lastIndexOf()
作用:從後往前找某個指定的字符串值在字符串中首次出現的位置
6. stringObject.substring()
作用:方法用於提取字符串中介於兩個指定下標之間的字符。
7. stringObject.toUpperCase()
作用:字母轉成大寫
8. stringObject.toLowerCase()
作用:字母轉成小寫
9.stringObject.split()
作用:方法用於把一個字符串分割成字符串數組
參數:(以什麼字符截取,保留數組到第幾位)
三種用法
var str="121314";
str.split("") //[1,2,1,3,1,4];
str.split("1")//[ ,2,3,4];
str.split("",2)//[1,2]
10.arrObject.join()
作用:方法用於把數組中的所有元素放入一個字符串。元素是通過指定的分隔符進行分隔的
兩種用法
var arr = [1,2,3];
arr.join("")//123
arr.join("-")//1-2-3
例題:高亮顯示查找的關鍵字
<input type="text" id="oin" />
<button>按鈕</button>
var oin = document.getElementById("oin");
var obtn = document.getElementsByTagName('button')[0];
var str = "arguments對象的長度是由實參個數而不是形參個數決定的。
形參是函數內部重新開辟內存空間存儲的變量,但是其與arguments對象
內存空間並不重疊。對於arguments和值都存在的情況下,兩者值是同步的
,但是針對其中一個無值的情況下,對於此無值的情形值不會得以同步。
如下代碼可以得以驗證。";
var h = "";
obtn.onclick = function() {
if (oin.value == "") {
alert("輸入為空");
return false
}
var s = oin.value;
if (str.indexOf(s) == -1) {
alert("沒有這個數字");
return false
}
var m = '<span style="background-color:red">' + s + '</span>';
str = str.split(s);
h = str.join(m)
document.body.innerHTML=h
}