简体   繁体   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);
}

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.

相关问题 如何从给定的 html 字符串中删除前导和尾随空格? - How to remove leading and trailing white spaces from a given html string? 如何从输入文本中删除前导和尾随空格? - How to remove leading and trailing white spaces from input text? 正则表达式与 javascript 中 email 地址的前导和尾随空格不匹配 - Regex to not match leading and trailing white spaces for email address in javascript 删除TinyMCE文本区域中的前导和尾随空格 - Remove leading and trailing white spaces in TinyMCE text area 使用正则表达式删除分隔符周围的尾随和前导空格 - Remove trailing and leading white spaces around delimiter using regex 修剪前导和尾随空间 - Trim Leading and Trailing Spaces 如何使用jquery限制文本框中前导和尾随空格的使用? - How to restrict use of Leading and Trailing spaces in the textbox using jquery? 如何从文本框输入中删除尾随和前导空格 - how to remove trailing and leading spaces from textbox input 如何验证tinymce textarea的前后空格? - how to validate tinymce textarea for preceding and trailing white-spaces? 如何删除字符串中的结尾空格而不是空格(开头也不要删除)? - How do I remove trailing white spaces but not white spaces within a string (nor at the beginning)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM