How to remove string trailing path separator in TypeScript

2 Answers

0 votes
function removeTrailingSeparator(path: string): string {
    return path.replace(/[\/\\]$/, '');
}

console.log(removeTrailingSeparator('path/to/project/'));
console.log(removeTrailingSeparator('path\\to\\project\\'));

 
     
/*
run:
     
"path/to/project" 
"path\to\project" 
     
*/

 



answered Jun 16, 2025 by avibootz
0 votes
function removeTrailingSeparator(path: string): string {
    if (path.endsWith('/') || path.endsWith('\\')) {
        return path.slice(0, -1);
    }
    return path;
}

console.log(removeTrailingSeparator('path/to/project/'));
console.log(removeTrailingSeparator('path\\to\\project\\'));

 
     
/*
run:
     
"path/to/project" 
"path\to\project" 
     
*/

 



answered Jun 16, 2025 by avibootz
...