user1071096
user1071096

Reputation: 155

How to check whether a string has whitespace at the beginning in javascript

I have a string as bellow

var str = "  Hello";

I can get the first character of the string as

var the_char=str.charAt(0);
alert(the_char)
if(the_char === " "){
    alert("first char of the query is space");
    return;
}

But the alert is not poping up.I want to pop up the alert if the first character of the string is a space.How can I do this?

Thanks

Upvotes: 2

Views: 12412

Answers (7)

Alexis Tyler
Alexis Tyler

Reputation: 949

You can use startsWith to check the first character of the string like so.

var str = "  Hello";
if (str.startsWith(" ")) {
    alert("first char of the query is space");
    return;
}

Upvotes: 0

Francesco
Francesco

Reputation: 99

Since JavaScripts String.trim() gets rid of whitespace well, I leveraged it to create a startsWithSpace() function.

var startsWithSpace = function(string) {
  return string.indexOf(string.trim()) != 0;
};

A new line is counted as whitespace in this implementation.

Upvotes: 2

Kabilan S
Kabilan S

Reputation: 1094

You dint return anything inside the if loop .. It gives syntax error so only your not getting popup..

remove the return statement

var str = "  Hello";

var the_char=str.charAt(0);
         alert(the_char);
         if(the_char === " "){
              alert("first char of the query is space");
             }

Upvotes: -2

user1106925
user1106925

Reputation:

There are several types of whitespace.

A regex will let you test for more than one...

alert(/^\s/.test(mystring));

The ^ character anchors the regular expression to the start of the string.

The \s will test for space, tab, carraige return, line feed, and more.


From MDN:

\s Matches a single white space character, including space, tab, form feed, line feed. Equivalent to [ \f\n\r\t\v​\u00A0\u1680​\u180e\u2000​\u2001\u2002​\u2003\u2004​\u2005\u2006​\u2007\u2008​\u2009\u200a​\u2028\u2029​\u2028\u2029​\u202f\u205f​\u3000].

Upvotes: 9

Silviu-Marian
Silviu-Marian

Reputation: 10907

function haswsatbeginning(str){var re=new RegExp('^[ \\s\u00A0]+','g');return((str+'').replace(re,'')!==str);}
var str = "  Hello";
alert(haswsatbeginning(str)); // alerts true

str = ('{^-^}');
alert(haswsatbeginning(str)); // alerts false

Upvotes: 0

PitaJ
PitaJ

Reputation: 15012

You're missing a semicolon after the first alert. If you're using Chrome or Firefox, you should always check the console for errors before you ask a question.

Upvotes: -1

Paul
Paul

Reputation: 141829

It does pop up:

JSFiddle

You probably have an Exception being thrown and not caught somewhere in between alerts like in this code which accesses x.x even though x is undefined:

JSFiddle

You need to track down and fix that error, rather than the code you posted here which works fine.

Upvotes: 0

Related Questions