Trim() function in javascript

In this javascript tutorial you will learn how to remove whitespace before /after the string using trim() function in javascript.

Let's have a look over below mentioned javascript custom function that will remove whitespace before/after the string.

function TrimString(str)

{

return str.replace(/^\s+|\s+$/g,"");

}

The calling of this function is very simple, you just have to provide string argument to this function.

I have developed an html web page in which I have a custom function for Trimming which is TrimString() and to call this TrimString() function I have made another function TrimMyString() and I am calling this TrimMyString() function via onclick event of hyperlink.

In this function first of all I declared a variable Myname and assign a string value to it but one thing must be noticed that there are some whitespace before/after the string value and then I calculate the length of that string and store the length in another variable len and then alert the length of the string before the trimming process. After this I used the function TrimString() to trim the string so that whitespace before/after string value can be removed and then again I calculate the length of string after trimming and then alert the length.

Now this time you will find the huge difference between two lengths before and after the trimming process and that difference will tell you how effective and efficient this simple javascript custom function is. Actually this custom function is using regular expression for trimming the whitespace before/after the string, means this function is capable of both ltrim and rtrim.

<html>

<head>

<title>Trim() function in javascript</title>

<script language="javascript" type="text/javascript">

function TrimString(str)

{

return str.replace(/^\s+|\s+$/g,"");

}

function TrimMyString()

{

var Myname,len;

Myname=" Adeel Fakhar ";

len=Myname.length;

alert(len);

Myname=TrimString(Myname);

len=Myname.length;

alert(len);

}

</script>

</head>

<body>

<a href="javascript:TrimMyString();" > Call Trim function</a>

</body>

</html>

So this is the way to trim the string in javascript using trim() function.

0 comments: