UNPKG

locutus

Version:

Locutus other languages' standard libraries to JavaScript for fun and educational purposes

21 lines (20 loc) 728 B
const escapeForCharClass = (chars) => chars.replace(/[\\\]^/-]/g, '\\$&'); export function trimright(str, chars) { // discuss at: https://locutus.io/tcl/trimright/ // parity verified: Tcl 8.6 // original by: Kevin van Zonneveld (https://kvz.io) // example 1: trimright(' hello ') // returns 1: ' hello' // example 2: trimright('__hello__', '_') // returns 2: '__hello' const value = String(str); if (chars === undefined) { return value.trimEnd(); } if (chars === '') { return value; } const escaped = escapeForCharClass(chars); const pattern = new RegExp(`[${escaped}]+$`, 'g'); return value.replace(pattern, ''); }