[英]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. 使用正则表达式和RegExp.test方法。
function checkBeginningWhiteSpace(str){
return /^\s/.test(str);
}
The \\s matches a single white space character, including space, tab, form feed and line feed. \\ s匹配单个空格字符,包括空格,制表符,换页符和换行符。
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;
这应该是您所需要的,除非
nbsp;
also needs to recognize as a space. 还需要识别为空间。
htmlStr1.match(/^\s+/)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.