说明 JavaScript 中的 String.trimStart() 和 String.trimEnd() 方法
String.trimStart() 方法用于从字符串前面移除空格,而 String.trimEnd() 方法则从字符串后面移除空格。
String.trimStart() 和 String.trimEnd() 方法的代码如下:
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result,.sample { font-size: 20px; font-weight: 500; } </style> </head> <body> <h1>String.trimStart() and String.trimEnd() methods</h1> <div&g;<pre class="sample"></pre></div> <div style="color: green;"><pre class="result"></pre></div> <button class="Btn">CLICK HERE</button> <h3> Click on the above button to trim the above string from start and end </h3> <script> let resEle = document.querySelector(".result"); let sampleEle = document.querySelector(".sample"); let str = " HELLO WORLD "; sampleEle.innerHTML = str; document.querySelector(".Btn").addEventListener("click", () => { resEle.innerHTML = "trimStart() :" + str.trimStart() + "|<br>"; resEle.innerHTML += "trimEnd() :" + str.trimEnd() + "|"; }); </script> </body> </html>
输出
上面的代码将产生以下输出:
点击“点击此处”按钮时:
广告