You can use a pattern with an alternation |
to match either what you want to remove at the start or at the end of the string by repeating it 1 or more time in a non capture group.
The repetition looks like this (?:@)+
for a single @ char, or like this (?:hello)+
for the word hello
If you want to make a function for it and want to pass any string, you have to escape the regex meta characters with a \
var x = '@@@hello world@@';
var y = 'hellohellohelloworld';
var z = '@@hello@world@@';
var a = '*+hello*+'
const customTrim = (strSource, strToRemove) => {
let escaped = strToRemove.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
return strSource.replace(new RegExp(`^(?:${escaped})+|(?:${escaped})+$`, 'g'), "")
};
console.log(customTrim(x, "\\s"));
console.log(customTrim(y, "hello"));
console.log(customTrim(z, "@"));
console.log(customTrim(a, "*+"));