开发者

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开发者_如何学Go 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.


You want to try using ^ -

/^\./

If you have

/\b\./

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


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) === "."
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜