How can I call a function directly on a string?
var test = function(x){
console.log(x);
};
test();
** The above logs 'undefined' as it should.
If I try:
"test".test();
I get:
"error"
"TypeError: \"test\".test is not a function.
But test is a function. So even if I try:
var example = "test";
example.test();
I get:
"error"
"TypeError: example.test is not a function
Any help is greatly appreciated.
5 Answers 5
To expand on the other answers a bit, you've created a function called test() but that function doesn't belong to any objects, and it doesn't belong to any Strings. You haven't defined a function called test() for Strings, hence the error.
To do that, you can try the following:
String.prototype.test = function() {
console.log(this);
};
"hello".test();
Read up here on prototypes. Essentially, objects in javascript have properties and methods, and they also have the properties and methods of their prototypes.
5 Comments
.test() is a method of RegExp object Yes, test is a function but String.prototype.test is not a function. The value is undefined and invoking an undefined value using invocation operator throws a TypeError.
Comments
The question is a bit unclear, but if you are trying to pass a String as your argument to the function, that would be
test("hello");
var example = "hello";
test(example);
2 Comments
x parameter should be set to the String in question. In languages with unified call syntax, a.test() is the same as test(a) or test a.you have to define function test() on the string first using Prototypes
For example:
String.prototype.cleanSpaces = function() {
return this.replace(" ", '');
};
now you can call "test ".cleanSpaces()
Comments
use prototype
String.prototype.test = function () {
console.log(this.toString());
}
'test'.test();
it would ouput test in console
Stringobject and then call that method on aStringtype value, see Luke's answer.test(the global variable) is a function, butexample.testor"test".test(the string properties) are not, as your error messages state.