Check if String starts with a space in JavaScript

javascript2 min read

Find out whether a string starts with a space or not using regex test method, string match method and startsWith method in JavaScript.

In this post, we will see how to check whether the first character in a string is a space or not using Javascript.

To check if a string starts with a space or not we can use:

  1. RegExp test method,
  2. String match method with regExp, or
  3. String startsWith method

Let's see the above-mentioned methods with examples.

Using RegExp.test() method

We can call the regex test method on the following expression \^\s*$\ and pass on the string to detect if the string starts with a white space or not in JavaScript.

Example

function startsWithSpace(str){ return /^\s/.test(str); } console.log(startsWithSpace(' hello')) // true console.log(startsWithSpace(' hello ')) // true console.log(startsWithSpace('hello')) //false

Here, we have called the test() method on the regular expression /^\s/ to match the pattern against the given string.

The / / (forward slash) indicates the start and the end of the expression.

The ^ indicate the start of a string or line.

The \s matches any whitespace characters in the string, like tab, space, newline, line feed, form feed, etc.

Using match() method on string with regex

The match() is used to match a string against a regular expression. If a match is found it returns the array with the matched result. And it returns null if no match is found.

Example:

function startsWithSpace(str){ return str.match(new RegExp( /^\s/)) !== null; } console.log(startsWithSpace(' hello')) //true console.log(startsWithSpace('hello')) //false

Here, we have used the match() method on a string and passed the regex as an argument to match against the given string.

/ and / indicate the start and end of the regular expression.

^ specifies the start of the string or a line

\s tells to check for white spaces in the string.

Using startsWith() method

The startsWith() method checks whether a string starts with a specific character in a given string. If the searched character is found it returns true else it returns false.

function startsWithSpace(str){ return str.startsWith(" "); } console.log(startsWithSpace(' hello')) //true console.log(startsWithSpace(' hello ')) //true console.log(startsWithSpace('hello'))// false console.log(startsWithSpace('hello '))// false

Related Topics:

JavaScript - Detect if a string contains any space

How to check if String contains only spaces in JavaScript

Related Posts