1

There is JQuery.trim() function but it is trimming the white spaces.

But I want to do it like in C#.

string props = ",width=400,height=400,status=0,location=0,";
props.Trim(',');
// result will be: "width=400,height=400,status=0,location=0"

How can I do this? Actually I would like to use it for general input param not only for ','..

uzay95
  • 16,052
  • 31
  • 116
  • 182

2 Answers2

1

Try an regexp:

var props=",width=400,height=400,status=0,location=0,";
props=props.replace(/^[,]*(.*?)[,]*$/, "$1");

If you, for example, also want to remove semicolons at the beginning or the end, use this:

props=props.replace(/^[,;]*(.*?)[,;]*$/, "$1");

And if you want to remove spaces, too, but only at the end:

props=props.replace(/^[,;]*(.*?)[,; ]*$/, "$1");
thejh
  • 44,854
  • 16
  • 96
  • 107
1

I found a link do this with functions and I found another link how to add this function to the String type. And I wrote below code and its test link :

String.prototype.TrimLeft = function (chars) {
    //debugger;
    var re = chars ? new RegExp("^[" + chars + "]+/", "g")
                   : new RegExp(/^\s+/);
    return this.replace(re, "");
}
String.prototype.TrimRight = function (chars) {
    var re = chars ? new RegExp("[" + chars + "]+$/", "g")
                   : new RegExp(/\s+$/);
    return this.replace(re, "");
}
String.prototype.Trim = function (chars) {
    return this.TrimLeft(chars).TrimRight(chars);
}

^[" + chars + "]+ is finding the characters at the begining of string. And it is replacing on this line: this.replace(re, "");

With this : [" + chars + "]+$, it is searching characters at the end of string g(globally) and replacing with the same method.

var c=",width=400,height=400,status=0,";
c.Trim(",");
// result: width=400,height=400,status=0
Community
  • 1
  • 1
uzay95
  • 16,052
  • 31
  • 116
  • 182
  • This will work, but there are powerful arguments to say that you shouldn't [modify objects you don't own](http://www.nczonline.net/blog/2010/03/02/maintainable-javascript-dont-modify-objects-you-down-own/). – lonesomeday Nov 21 '10 at 12:29
  • 1
    I didn't read it yet but I will. Thank your for your comment. – uzay95 Nov 21 '10 at 12:37