簡體   English   中英

如何減少前導空格和尾隨空格

[英]how to curtail leading and trailing white spaces

var str = "    abcd    ";

if(str.match(/\ /)) { 
    document.writeln("String Empty");
} else {
    document.writeln("Length :  ");
    document.writeln(str.length);
}

上面的代碼盡管中間包含字符,但始終返回空字符串。

我需要砍掉開頭和結尾的空格。

// Remove leading and trailing whitespace
// Requires jQuery
var str = " a b    c d e f g ";
var newStr = $.trim(str);
// "a b c d e f g"

// Remove leading and trailing whitespace
// JavaScript RegEx
var str = "   a b    c d e f g ";
var newStr = str.replace(/(^\s+|\s+$)/g,'');
// "a b c d e f g"

// Remove all whitespace
// JavaScript RegEx
var str = " a b    c d e   f g   ";
var newStr = str.replace(/\s+/g, '');
// "abcdefg"

使用修剪並檢查長度:

if (!str.trim().length) { 
  document.writeln("String Empty");
}
else {
 document.writeln("Length : ");
 document.writeln(str.trim().length);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM