views:

6412

answers:

3

I need to substring a variable, and not an object, I know objects such as;

$("div#foo").text().substr(0,1);

But I need to do it on a non-object, for example a variable;

var foo = 'abc';
foo = foo.substr(0,1);

The second example won't work, because it's a non object. The actual problem is that I need to cut the last character off from a string, so is it possible to do this in jQuery on a non-object?

+3  A: 
var foo = 'abc';
foo.substring(0, 1);
RaYell
Wierd though, that worked. But when I tried it before, I got "foo.substring is not a function" and it told me that I need to do it on an object. But all of a sudden it works and now I feel pretty stupid because that was the first thing I tried, without success. xD Thanks.
Stefan Konno
Did you case substring correctly? I sometimes do subString and this will choke.
Adrian Lynch
`substring` (all lowercase) is the correct syntax: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/substring Remember that JS is case-sensitive
RaYell
A: 

In Javascript, a String is actually also some kind of an object. As such, it has its own member functions, and substring() is one of them. Use the syntax RaYell provided to achieve what you want :-)

JorenB
A: 

I think that maybe you are receiving that message ("foo.substring is not a function") because when you declared the foo variable you wrote $foo instead of var foo. That's the reason why it is interpreted as a jQuery variable instead of a javascript variable

Juan