如何使用 JavaScript trim 方法,附示例
這個簡單的教程將向您展示如何使用 JavaScript 字符串 trim() 方法並舉例說明。
修剪 ()* 方法可用於 JavaScript 中的任何字符串類型變量。它會刪除字符串開頭和結尾的所有空白(空格、製表符、換行符)。
為什麼這有用? 有時你會用一堆不需要的空白填充你的字符串——通常來自最終用戶在不需要空格時敲擊空格鍵。在拆分字符串或從文件中讀取字符串後,也會出現不必要的空白。
在顯示字符串或將它們存儲到數據庫之前從字符串中刪除不需要的空格,可以使您的數據保持整潔。
JavaScript 修剪方法語法
使用 trim() 的語法 字符串變量的方法如下:
string.trim()
注意:
- 字符串 可以是任何字符串類型的變量
- trim() 之後 方法已在字符串上執行,則返回修剪後的字符串。
- 原字符串變量沒有被修改!
修剪方法示例
下面是一些代碼,顯示了 trim() 方法的行為。我會在評論中留下解釋:
# Define a string variable with a bunch of unnecessary white space at the beginning and end var myString = " spaces everywhere around me! "; # Assign the value returned from the trim() method to a new variable var myTrimmedString = myString.trim(); # When viewing the original string, you will notice that it has not been modified by trim() console.log(myString); # " spaces everywhere around me! " # The returned trimmed value was assigned to the new string variable console.log(myTrimmedString); # "spaces everywhere around me!"
......這就是它的全部內容。簡單但非常有用!
您可以在 Mozilla 開發人員文檔中查看有關 trim() 方法的更多信息。