[英]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);
}
The above code always returns an empty string although it has characters in between. 上面的代码尽管中间包含字符,但始终返回空字符串。
I need to chop the leading and trailing white spaces. 我需要砍掉开头和结尾的空格。
// 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"
Use trim and check the length: 使用修剪并检查长度:
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.