I want to remove not only spaces, but certain characters aswell from the beginning or end of a javascript string.
function trim(str, characters) {
var c_array = characters.split('');
var result = '';
for (var i=0; i < characters.length; i++)
result += '\\' + c_array[i];
return str.replace(new RegExp('^[' + result + ']+|['+ result +']+$', 'g'), '');
}
So the function can be used as follows: trim(' - hello** +', '+*- ');
The escaping is required as + * .
etc. would be used in the regular expression. Is there a better way to trim any character in javascript? Or a better way to do the escaping, as not every character needs it.