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"
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
asked Jan 19, 2010 at 20:12
James NineJames Nine
2,61811 gold badges38 silver badges54 bronze badges
2 Answers
Reset to default 6Use 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.
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+/)