Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there anyway to detect if a JavaScript object is a regex?

For example, I would like to do something like this:

var t = /^foo(bar)?$/i;
alert(typeof t); //I want this to return "regexp"

Is this possible?

Thanks!

EDIT: Thanks for all the answers. It seems I have two very good choices:

obj.constructor.name === "RegExp"

or

obj instanceof RegExp

Any major pros/cons to either method?

Thanks again!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
149 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use instanceof operator:

var t = /^foo(bar)?$/i;
alert(t instanceof RegExp);//returns true

In fact, that is almost the same as:

var t = /^foo(bar)?$/i;
alert(t.constructor == RegExp);//returns true

Keep in mind that as RegExp is not a primitive data type, it is not possible to use typeof operator which could be the best option for this question.

But you can use this trick above or others like duck type checking, for example, checking if such object has any vital methods or properties, or by its internal class value (by using {}.toString.call(instaceOfMyObject)).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...