给定以下字符串:

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"

最佳答案

使用regular expressionsRegExp.test方法。

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


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

09-11 18:26
查看更多