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

时间:2010-01-19 20:12:42

标签: javascript jquery html string whitespace

给出以下字符串:

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"

2 个答案:

答案 0 :(得分:6)

使用regular expressionsRegExp.test方法。

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

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

答案 1 :(得分:1)

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

htmlStr1.match(/^\s+/)