gargantuan
gargantuan

Reputation: 8944

How to add placeholders to strings in javascript

I'd like to be able to set default placeholders for string really easily like this

someString.placeholder("waiting for text") 

Which could be used like this...

$("p.some-class").html( someString.placeholder("waiting for text") );

so if 'someString' is empty, the user sees "Waiting for text", but if the string has a length greater than 0, they see the actual string.

I've tried to extend the String object like this

String.prototype.placeholder = function(placeholder){

    return (this.length > 0) ? 
    this : 
    "<span class=\"placeholder-string\">" + placeholder + "</span>";

}

but that doesn't appear to be working. Any thoughts anyone?

Here's a JSFiddle for anyone who's interested.

Upvotes: 0

Views: 2525

Answers (1)

pimvdb
pimvdb

Reputation: 154908

It appears that this is a String object, not the primitive version. You'd have to convert it into a primitive. Also you can eliminate > 0:

String.prototype.placeholder = function(placeholder){

    return this.length ? 
    this + "" : 
    "<span class=\"placeholder-string\">" + placeholder + "</span>";

}

Upvotes: 1

Related Questions