首頁  >  文章  >  web前端  >  如何在 JavaScript 中修剪字串的開頭或結尾?

如何在 JavaScript 中修剪字串的開頭或結尾?

WBOY
WBOY轉載
2023-08-29 13:57:021061瀏覽

如何在 JavaScript 中修剪字符串的开头或结尾?

在處理資料時,有必要從字串中刪除不必要的空格。因此,我們需要在開頭或結尾處修剪字串。

如果我們在資料中保留不必要的空格,可能會​​導致一些問題。例如,在儲存密碼時,如果我們不修剪空格,當使用者嘗試其他時間登入應用程式時,密碼可能會不符。

在本教程中,我們將學習在 JavaScript 中修剪字串的開頭或結尾。

使用trimRight()方法修剪字串的結尾

trimRight() 方法允許我們刪除字串末尾的空格。

文法

使用者可以按照下面的語法使用trimRight()方法從末尾修剪字串。

let result = string1.trimRight(); 

在上面的語法中,string1是一個從末尾開始修剪的字串,我們將最終的字串儲存在結果變數中。

範例 1

在下面的範例中,我們建立了兩個字串,它們在字串的開頭和結尾處包含空格。之後,我們使用trimRight()方法刪除字串末尾的空格。

<html>
<body>
   <h2>Using the <i> trimRight() </i> method to trim the string from the end in JavaScript.</h2>
   <div id = "output"></div>
   <br>
</body>
<script>
   let output = document.getElementById("output");
   let string1 = " Trim from right! ";
   let string2 = "Trim from the end ! ";
   string1 = string1.trimRight();
   string2 = string2.trimRight();
   output.innerHTML += "The final string1 is *" + string1 + "*. <br>";
   output.innerHTML += "The final string2 is *" + string2 + "*. <br>";
</script>
</html>

使用trimLeft()方法修剪字串的開頭

我們可以使用trimLeft()方法從頭開始修剪字串。

文法

使用者可以按照下面的語法使用trimLeft()方法刪除字串開頭的空格。

let pass1 = pass1.trimLeft(); 

在上面的語法中,我們使用了帶有pass1字串的trimLeft()方法。

範例 2

在下面的範例中,我們有兩個開頭包含空格的密碼字串。之後,我們使用trimLeft()方法刪除字串開頭的空格。

使用者可以觀察輸出開頭沒有空格的字串。

<html>
<body>
   <h2>Using the <i> trimLeft() </i> method to trim the string from the start in JavaScript.</h2>
   <div id = "output"></div>
   <br>
</body>
<script>
   let output = document.getElementById("output");
   let pass1 = " abcd@123 "
   let pass2 = " pok.=-E3434";
   pass1 = pass1.trimLeft();
   pass2 = pass2.trimLeft();
   output.innerHTML += "The final string1 is *" + pass1 + "*. <br>";
   output.innerHTML += "The final string2 is *" + pass2 + "*. <br>";
</script>
</html> 

使用trim()方法將字串的左端和右端一起修剪

字串庫的trim()方法允許我們一次刪除字串開頭和結尾的所有空格,而不是單獨使用trimLeft()和trimRight()方法。

文法

使用者可以按照下面的語法使用trim()方法修剪字串的開頭或結尾。

str = str.trim();

在上面的語法中,str 是一個在字串的開頭和結尾處包含空格的字串。

範例 3

在下面的範例中,我們允許使用者在提示框中輸入帶有空格的字串。之後,我們使用trim()方法刪除空格並在輸出中顯示最終結果。

<html>
<body>
   <h2>Using the <i> trim </i> method to trim the string from the start in JavaScript.</h2>
   <div id = "output"></div>
   <br>
</body>
<script>
   let output = document.getElementById("output");
   let str = prompt("Enter the string with white spaces at start and end.", " abcd efg ")
   str = str.trim(); 
   output.innerHTML += "The final string1 is *" + str + "*. <br>";
</script>
</html>

我們學會了使用各種方法從頭到尾修剪字串。其中trimLeft()方法用於從左側修剪字串,trimRight()方法用於從右側修剪字串。此外,我們使用trim()方法來修剪開頭和結尾的空格。

此外,使用者還可以使用trimStart()和trimEnd()方法從兩端修剪字串。

以上是如何在 JavaScript 中修剪字串的開頭或結尾?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除