JavaScript 處理字串

來源:互聯網
上載者:User
JavaScript 處理字串雖然 JavaScript 有很多用處,但是處理字串是其中最流行的一個。下面讓我們深入地分析一下使用 JavaScript 操作字串。在 JavaScript 中, String 是對象。 String 對象並不是以字元數組的方式儲存的,所以我們必須使用內建函數來操縱它們的值。這些內建函數提供了不同的方法來訪問字串變數的內容。下面我們詳細看一下這些函數。 

包羅永珍 

操作字串的值是一般的開發人員必須面臨的家常便飯。操作字串的具體方式有很多,比如說從一個字串是提取出一部分內容來,或者確定一個字串是否包含一個特定的字元。下面的 JavaScript 函數為開發人員提供了他們所需要的所有功能: 

•  concat() – 將兩個或多個字元的文本組合起來,返回一個新的字串。 

•  indexOf() – 返回字串中一個子串第一處出現的索引。如果沒有匹配項,返回 -1 。 

•  charAT() – 返回指定位置的字元。 

•  lastIndexOf() – 返回字串中一個子串最後一處出現的索引,如果沒有匹配項,返回 -1 。 

 
 
•  match() – 檢查一個字串是否匹配一個Regex。 

•  substring() – 返回字串的一個子串。傳入參數是起始位置和結束位置。 

•  replace() – 用來尋找匹配一個Regex的字串,然後使用新字串代替匹配的字串。 

•  search() – 執行一個Regex匹配尋找。如果尋找成功,返回字串中匹配的索引值。否則返回 -1 。 

•  slice() – 提取字串的一部分,並返回一個新字串。 

•  split() – 通過將字串劃分成子串,將一個字串做成一個字串數組。 

•  length() – 返回字串的長度,所謂字串的長度是指其包含的字元的個數。 

•  toLowerCase() – 將整個字串轉成小寫字母。 

•  toUpperCase() – 將整個字串轉成大寫字母。 

注意: concat 、 match 、 replace 和 search 函數是在 JavaScript 1.2 中加入的。所有其它函數在 JavaScript 1.0 就已經提供了。 

下面讓我們看一下如何在 JavaScript 使用這些函數。下面的代碼是用到了前面提到的所有函數: 

function manipulateString(passedString1, passedString2) { 

var concatString; 

// The string passed to concat is added to the end of the first string 

concatString = passedString1.concat(passedString2); 

alert(concatString); 

// The following if statement will be true since first word is Tony 

if (concatString.charAt(3) == "y") { 

alert("Character found!"); 

// The last position of the letter n is 10 

alert("The last index of n is: " + concatString.lastIndexOf("n")); 

// A regular expression is used to locate and replace the substring 

var newString = concatString.replace(/Tony/gi,"General"); 

// The following yields Please salute General Patton 

alert("Please salute " + newString); 

// The match function returns an array containing all matches found 

matchArray = concatString.match(/Tony/gi); 

for (var i=0; i

alert("Match found: " + matchArray[i]); 

// Determine if the regular expression is found, a –1 indicates no 

if (newString.search(/Tony/) == -1) { 

alert("String not found"); 

} else { 

alert("String found."); 

// Extract a portion of the string and store it in a new variable 

var sliceString = newString.slice(newString.indexOf("l")+2,newString.length); 

alert(sliceString); 

// The split function creates a new array containing each value separated by a space 

stringArray = concatString.split(" "); 

for (var i=0; i

alert(stringArray[i]; 

alert(newString.toUpperCase()); 

alert(newString.toLowerCase()); 

下面是執行上面的代碼得到的結果: 

Tony Patton 
Character Found! 
The last index of n is: 10 
Match found: Tony 
Please salute General Patton 
String not found 
Patton 
Tony 
Patton 
GENERAL PATTON 
general patton 

範例程式碼把所有這些提到的函數都用到了。 

特殊字元 

除了這些函數之外,還有很多的特殊字元可以用來表示關鍵的效果。這些特殊字元包括: 

•  \t – 跳格鍵 

•  \b – 退格 / 刪除 

•  \r – 斷行符號 

•  \n – 換行 

•  \f – 換頁 

特殊字元最常見的用途就是格式化輸出。例如,你可能需要在輸出中插入一個換行來正確地顯示一個值。而且,在換行時也需要斷行符號。在一些平台上,“ \n ”已經足夠產生換行效果了,而在一些機器上要正確地顯示一個換行則需要“ \r\n ”。下面的例子顯示了在一個多行視窗上顯示的特殊字元: 

var output = null; 
output = "Special Characters"; 
output += "\n"; 
output += "==============="; 
output += "\n"; 
output += "\\t - tab"; 
output += "\n"; 
output += "\\b - backspace/delete"; 
output += "\n"; 
output += "\\r - carriage return"; 
output += "\n"; 
output += "\\n - newline"; 
output += "\n"; 
output += "\\f - form feed"; 
output += "\n"; 
alert(output); 

前面的例子使用加號來連接字串,而沒有使用 concat 函數。原因很簡單,對於 concat 函數來說,每一個操作都需要一個新的變數;反之,我們這裡用的這種方法則簡單地擴充了原有的值,而不需要新的變數。而且,樣本中使用換碼符來正確地顯示特殊字元。系統將一個反斜線當作一個訊號,認為它後面會跟一個特殊字元,但是連著兩個反斜線則抵消這種操作。輸出中的每個字元都通過 newline 特殊字元被顯示在新的一行。 

添加到工具箱中 

特殊字元和函數可以與其它 JavaScript 技巧結合起來解決很多問題。其中一種情況是用來進行 JavaScript 用戶端表單驗證,這篇文章中提出的方法可以簡單地用來實現表單驗證。 

下面的代碼將在一個表單被提交時調用。要提交的表單包含三個域:名稱、地址和郵遞區號。為了實現起來比較簡單,我們只驗證每個域都不可為空,並且郵遞區號必須是數字。下面的 JavaScript 程式碼完成這一功能: 

function validation() { 

var doc = document.forms[0]; 

var msg = ""; 

if (doc.Name.value == "") { 

msg += "- Name is missing\n"; 

if (doc.Address.value == "") { 

msg += "- Address is missing\n"; 

if (doc.ZipCode.value == "") { 

msg += "- Zip code is missing\n"; 

var zip = new String(doc.ZipCode.value); 

if (zip.search(/<0-9][0-9][0-9][0-9][0-9]$/)==-1) { 

msg += "- Enter valid Zip code"; 

if (msg == "") { 

doc.submit; 

} else { 

msg = "Please correct the following validation errors and re-submit:\n\n" + msg; 

alert(msg); 

在使用者提交表單時,這個函數就會被調用。對函數的調用是在一個 HTML 按鈕的 onSubmit 事件中實現的。 

 

驗證函式檢查每個域是否為空白。如果發現了一個空值,那麼就會在驗證訊息變數 msg 後面添加一個出錯訊息。此外,還使用了一個Regex來驗證郵遞區號域的格式。在這裡,我們只接受五位元的美國地區郵遞區號。如果發現有任何錯誤(即 msg 變數不為空白),那麼程式就會顯示一個錯誤訊息;否則的話,程式就會提交表單

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.