1

I have a JavaScript function that uses document.getElementById(). I want to upgrade it to be able to use jQuery selectors ($(this).parent().find("blah")), however it needs to be able to use the original method for backwards compatibility. Is there a way I can test if the argument passed to the function is a string (so I can use getElementById) or a jQuery object (not a string).

I could use .length, but is this a failsafe method of determining whether the argument is a string?

As long as I can test for strings, the jQuery branch can just go in an else - I don't need to make absolutely sure it's not a string, although it would be nice to test if it's jQuery too.

Thanks,

James

Eric
  • 95,302
  • 53
  • 242
  • 374
Bojangles
  • 99,427
  • 50
  • 170
  • 208

5 Answers5

4

following code returns true:

"somestring".constructor == String
decyclone
  • 30,394
  • 6
  • 63
  • 80
3
Object.prototype.toString.call(your_argument) == "[object String]"
Eric
  • 95,302
  • 53
  • 242
  • 374
anton_byrna
  • 2,477
  • 1
  • 18
  • 31
  • Thanks :-) I tried decyclone's answer and had a bit of trouble. Yours works great though. – Bojangles Dec 11 '10 at 11:58
  • Thanks for the great answer, can you comment on how this compares to using typeof? –  Jan 15 '13 at 16:49
  • @pure_code good explanation http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/ – anton_byrna Jan 16 '13 at 15:37
2

Is this what you're after?

var str = "blah";
if (typeof str == "string") {

} else {


}

And length is definitely not the way to go. Arrays will also have a length property, not to mention any custom object could as well.

David Tang
  • 92,262
  • 30
  • 167
  • 149
0

I think instanceOf is what you are looking for. See this post: What is the instanceof operator in JavaScript?

Community
  • 1
  • 1
Austin Lin
  • 2,545
  • 17
  • 17
  • 1
    This will only work for strings converted into an Object, e.g. through `new String("test")`, not primitives. – David Tang Dec 11 '10 at 11:03
0

JavaScript has two kinds of strings. This checks for both kinds.

function isString (str)
{
  return str instanceof String || typeof str === 'string';
}

This will throw always a ReferenceError, if the argument is undeclared although typeof would not throw an error, because JavaScript evaluates from left to right (see Short-circuit evaluation).

ceving
  • 21,900
  • 13
  • 104
  • 178