I want to remove not only spaces, but certain characters, as well 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'), '');
}
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?