zjmiller
zjmiller

Reputation: 2807

How do I use a regular expression in JavaScript to see if a string begins with a period?

I'm new to regular expressions.

The following code works as expected, printing first "true" and then "false", the backslash in front of the period escaping it:

var pattern = new RegExp(/\./);
document.write(pattern.test("."));
document.write(pattern.test("a"));

But why does the following print "false":

var pattern = new RegExp(/\b\./);
document.write(pattern.test("."));

The period is, after all, at the beginning of the string.

Upvotes: 3

Views: 92

Answers (2)

RightSaidFred
RightSaidFred

Reputation: 11327

It doesn't work because to have a word break, you first need to have a word.

Using a \b, this would work:

var pattern = new RegExp(/a\b\./);
document.write(pattern.test("a."));

If all you're doing is testing the first character, you can do it without a regex if you'd like.

".".charAt(0) === "."

Upvotes: 1

manojlds
manojlds

Reputation: 301347

You want to try using ^ -

/^\./

If you have

/\b\./

it matches the .'s in Hello. How are you.

Upvotes: 5

Related Questions