views:

225

answers:

2

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"
A: 

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.

htmlStr1.match(/^\s+/)
Stefan Kendall
+4  A: 

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.

Rafael
This only checks to see if there is one whitespace. You really want /^\s+/
Keith Rousseau
it is enough to check only the first character to be sure that a string beginns with white space.
Rafael
Rafael is right, I only needed to check one whitespace.
James Nine
Yeah, sorry I was thinking of the case where you want to remove leading whitespace.
Keith Rousseau