![](/img/trans.png)
[英]How to remove leading and trailing white spaces from a given html string?
[英]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.