Monday, January 9, 2012

StartsWith(), EndsWith(),Trim() String functions in JavaScript


There is no direct method in JavaScript to make our work easy. But we can create our own prototype for String functions, then we can use it as like as normal method like in C#, VB.Net , etc…
For that we need define the prototype first within the <script>, see here is the example of prototype.

In JavaScript
        String.prototype.startsWith = function (str)
        { return (this.match("^" + str) == str) }

        String.prototype.endsWith = function (str)
        { return (this.match(str + "$") == str) }

        String.prototype.trim = function () {
            return
            (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))
        }

Then we can create a function in JavaScript and use these functions. Like String.prototype we can create prototype for all object in JavaScript.
In JavaScript
function check() {

        var mymsg="This is my world";

        if (mymsg.startsWith("This"))//return ture if string startsWith parameter string
        {
            alert("This msg starts with this");
        }
        else {
            alert("This msg not starts with this");
        }

        if (mymsg.endsWith("world"))//return ture if string endswith parameter string 
        {
            alert("This msg ends with world");
        }
        else {
            alert("This msg not ends with world");
        }

In Design
     <asp:Button ID="Button1" runat="server" Text="Check" OnClientClick="check();return false" />   

I hope this article will be very helpful to all. Thanks for reading this article.

“Keep reading and share the knowledge”  
“Grow more trees to save the Earth”

No comments:

Post a Comment