最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 6

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+/)
发布评论

评论列表(0)

  1. 暂无评论