Take the 2-minute tour ×

Given the following 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> ";

Is there a way to write a function that can detect if this string has a whitespace in the very beginning only?

e.g., it should do the following:

alert( checkBeginningWhiteSpace(htmlStr1) ); // should return "true"
alert( checkBeginningWhiteSpace(htmlStr2) ); // should return "false"
share|improve this question
add comment

2 Answers

up vote 5 down vote accepted

Use regular expressions and the RegExp.test method.

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

The \s matches a single white space character, including space, tab, form feed and line feed.

share|improve this answer
This only checks to see if there is one whitespace. You really want /^\s+/ –  Keith Rousseau Jan 19 '10 at 20:53
it is enough to check only the first character to be sure that a string beginns with white space. –  Rafael Jan 19 '10 at 21:12
Rafael is right, I only needed to check one whitespace. –  James Nine Jan 19 '10 at 23:19
Yeah, sorry I was thinking of the case where you want to remove leading whitespace. –  Keith Rousseau Jan 20 '10 at 14:54
add comment

This regex should match the beginning of the line, followed by one or more space characters (including tabs). This should be what you need, unless nbsp; also needs to recognize as a space.

share|improve this answer
add comment

Your Answer


