How would I replace every occurrence of a character in a string with --[character]--
in es6
preferably.
Example string: tb23a
Pattern: t3a
Expected output: --t--b2--3----a--
CodePudding user response:
function repleceEveryChar(value, options) {
const { chars = '', leading = '', trailing = '' } = options;
return (chars && String(value).replace(
RegExp(`\[${ chars }\]`, 'g'),
match => `${ leading }${ match }${ trailing }`
)) || value;
}
console.log(
"repleceEveryChar('tb23a', { chars: 't3a', leading: '--', trailing: '--' }) ...",
repleceEveryChar('tb23a', { chars: 't3a', leading: '--', trailing: '--' })
);
console.log(
"repleceEveryChar('tb23a', { chars: 'b2', leading: '*', trailing: ' ' }) ...",
repleceEveryChar('tb23a', { chars: 'b2', leading: '*', trailing: ' ' })
);
console.log(
"repleceEveryChar('foobar', { leading: '*', trailing: ' ' }) ...",
repleceEveryChar('foobar', { leading: '*', trailing: ' ' })
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>