JavaScript的字串方法匯總_基礎知識

來源:互聯網
上載者:User

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("")//123arr.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  }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.