繁体   English   中英

在Javascript或jQuery中,如何检测字符串开头的空格?

[英]In Javascript or jQuery, how to detect whitespace in beginning of string?

给定以下字符串:

htmlStr1 = " <div>This is a string with whitespace in the beginning</div> ";
htmlStr2 = "<div>This is a string with no whitespace in the beginning</div> ";

有没有一种方法可以编写一个函数来检测此字符串是否仅在开始时就有空格?

例如,它应该执行以下操作:

alert( checkBeginningWhiteSpace(htmlStr1) ); // should return "true"
alert( checkBeginningWhiteSpace(htmlStr2) ); // should return "false"

使用正则表达式RegExp.test方法。

function checkBeginningWhiteSpace(str){
   return /^\s/.test(str);
}

\\ s匹配单个空格字符,包括空格,制表符,换页符和换行符。

此正则表达式应与行的开头匹配,后跟一个或多个空格字符(包括制表符)。 这应该是您所需要的,除非nbsp; 还需要识别为空间。

htmlStr1.match(/^\s+/)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM