简体   繁体   中英

In Javascript or jQuery, how to detect whitespace in beginning of string?

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?

eg, it should do the following:

alert( checkBeginningWhiteSpace(htmlStr1) ); // should return "true"
alert( checkBeginningWhiteSpace(htmlStr2) ); // should return "false"

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.

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+/)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM