How to use regex in JavaScript to find out if a string starts with a period?

I am new to regular expressions.

The following code works as expected, first prints β€œtrue” and then β€œfalse”, the backslash before the period that eludes it:

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

But why is the following print "false":

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

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

+3
source share
2 answers

Do you want to try using ^-

/^\./

If you

/\b\./

he matches .inHello. How are you.

+5
source

This does not work, because in order to break a word, you must first have a word.

Using \b, this will work:

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

, , , , .

".".charAt(0) === "."
+1

All Articles