Gerald Anekwe
Gerald Anekwe

Reputation: 46

Call function ON a string (Javascript)

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.

Upvotes: 0

Views: 105

Answers (5)

Luke
Luke

Reputation: 1724

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.

Upvotes: 3

Alien
Alien

Reputation: 3678

use prototype

 String.prototype.test = function () {
    console.log(this.toString());
}

'test'.test();

it would ouput test in console

Upvotes: 0

Thilo
Thilo

Reputation: 262494

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);

Upvotes: 1

Amit
Amit

Reputation: 26266

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()

Upvotes: 0

Ram
Ram

Reputation: 144689

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.

Upvotes: 1

Related Questions