简体   繁体   English

在Javascript或jQuery中,如何检测字符串开头的空格?

[英]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.

相关问题 如何在JavaScript中检测字符串中的空格 - How to detect whitespace in a string in javascript 如何在javascript中检查字符串开头是否有空格 - How to check whether a string has whitespace at the beginning in javascript 使用jQuery或javascript从网页中存在的所有文本框的字符串开头和结尾删除空格 - Remove whitespace from beginning and end of string of all textbox present in a webpage using jQuery or javascript 使用 javascript/jquery 删除字符串的开头 - Remove beginning of String with javascript/jquery 在Javascript / jQuery中,如何检查字符串的特定部分并确定它是空格还是字母? - in Javascript/jQuery, how to check a specific part of a string and determine if it is a whitespace or letter? 字符串替换正则表达式,开头是空格 - String Replace Regex, Whitespace in the Beginning 使用 javascript 或 jQuery,我如何检测未使用的“空白”屏幕房地产? - Using javascript or jQuery, how I can detect unused “whitespace” screen realestate? regex - 忽略字符串开头的空格 - regex - ignore whitespace from the beginning of the string 如何在JavaScript中检测Unicode中的不可见字符(零宽度或空格) - How to detect invisible (zero-width or whitespace) characters in Unicode in JavaScript 如何在javascript中从正则表达式的开头开始拆分字符串 - How to split a string starting at the beginning of a regex in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM