1

i want to define my own custom properties for string object .so that i can use this properties directly on string objects. eg:- str is my string object.then i should be able to use .IsNull property as shown below.

var str = “string”;

str.IsNull; //returns true if null

str.IsEmpty; returns true if empty
2
  • A string can't be null (strings and null are different types). Commented Sep 12, 2016 at 7:17
  • C# allows null string.thanks didn't know this that js don't have null strings Commented Sep 12, 2016 at 9:50

4 Answers 4

3

You can explore prototype property

For example

String.prototype.yourMethod = function(){
 // Your code here
}
Sign up to request clarification or add additional context in comments.

4 Comments

Please note that you can't check if a string is null with a method in the String prototype, because the type would be null and not String.
But your example adds a method; the OP is trying to add properties (or perhaps getter methods that seem like properties to the client code).
why can't string be null in js?
@PawanWagh Because null is a type just like string. It cannot be of both types at the same time. It's eigher a string, maybe an empty one, or it is null (or undefined, which is something else too)
3

thanks to all of you for your help.but i got the way

Object.defineProperty( String.prototype, 'IsNullOrEmpty', {
    get: function () {
        return ((0 === this.length) || (!this) || (this === '') || (this === null));
    }
});

var str = "";
str.IsNullOrEmpty;//returns true

Comments

1

You have to add a new method to a String wrapper object's prototype. The best practice is to check if the method already exists before declaring it. For instance:

String.prototype.yourMethod = String.prototype.yourMethod || function() {
    // The body of the method goes here.
}

1 Comment

I don't see how "checking" if the method exists helps if you then just proceed blindly on the assumption that the pre-existing method will work exactly the same way as the one you're trying to add. (Should be fine if polyfilling standard JS methods for older browsers, but could go horribly wrong for custom methods.)
1

I would personally make functions for this instead of extending the prototype.

If you extend the prototype, you have to make sure you add them to all types you want to check, it goes beyond the String object.

function isNull(str) {
  console.log( str === null );
}

function isEmpty(str) {
  console.log( typeof str == 'string' && str === '' );
}


isNull(null);
isNull('');
isNull('test');

isEmpty(null);
isEmpty('');
isEmpty('test');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.