Today I want to share a javascript function that will trim any character from the beginning and the end of the string.
The function will trim all occurrences of the character from the beginning and the end of the string.

function trim_chars(str, char)
{

while (str.substr(0, 1) == char)
str = str.substr(1);

var nrt = str.length;
while (str.substr(nrt-1, 1) == char)
{
str = str.substr(0, nrt-1);
}

return str;
}

The function will be used like this:

trim_chars('/public_html/images/', '/');

In this case it will trim the ‘/’ from the beginning and the end of the string leaving: public_html/images

If you would like to trim the characters only from the beginning of the string, the function would look like this:

function trim_chars_start(str, char)
{
while (str.substr(0, 1) == char)
str = str.substr(1);

return str;
}

If you would like to trim only the last characters:

function trim_chars(str, char)
{
var nrt = str.length;
while (str.substr(nrt-1, 1) == char)
{
str = str.substr(0, nrt-1);
}

return str;
}