检查一行只包含空格和\ n在js / node.js

我当前正试图parsing一个smil(xml)文件。

我所遇到的最大的问题是,如果行不包含任何内容,但空白和行结束。

我试着:

if(line.trim()==='\n') if(line.trim().length<='\n'.length) n='\n'; if(line.trim()===n) 

他们都没有工作。 有没有办法来检查一个string中是否没有“真正的”字符? 或者如果string只包含\ t,\ n和空格?

阅读正则expression式的一些教程,然后尝试这个

  if (/^\s*$/.test(line)) console.log('line is blank'); 

/^\s*$/是一个正则expression式

  ^ anchor begin of string \s whitespace character class (space, tab, newline) * zero or more times $ end of string 

修剪删除所有的领先和尾随WHITESPACES 。 我认为它也会删除\ n和\ t。 修剪后应检查string的长度是否为零。 如果长度不为零,则string必须包含除空格以外的其他字符。

正如你所提到的关于Node.js 如果修剪不工作,那么你可以通过执行下面的代码来实现修剪:

 if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); }; } 

我会尝试一种不同的方法; find你之后的字符的types。

 var lineR = line.search(char(34)) //char(34) is carriage return if(lineR != null) //lineR is your actual position of lineReturn. Do a Substring(0,lineR) then. line = line.Substring(0,lineR) 

或者,查看.lastIndexOf()。 http://www.w3schools.com/jsref/jsref_lastindexof.asp