i want to create user defined function to trim a word in Javascript
how can i trim the word in Javascript.....??开发者_StackOverflow?
If you can use jQuery, simply use $.trim()
.
If not, just add a trim method to the String prototype if the browser doesn't support it natively:
if(!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^[\s\xA0]+/, '').replace(/[\s\xA0]+$/, '')
}
}
Then you can use var newstring = somestring.trim();
If by trim
, you mean remove extra whitepace, put this at the top of your script
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
And use it like this
var thestring = " hello ";
alert(thestring.trim());
You can add the function below // Trim function in javascript
function Trim(str)
{
while (str.substring(0,1) == ' ') // check for white spaces from beginning
{
str = str.substring(1, str.length);
}
while (str.substring(str.length-1, str.length) == ' ') // check white space from end
{
str = str.substring(0,str.length-1);
}
return str;
}
Hope it helped...
精彩评论