Home > Software design >  Encrypt using regex
Encrypt using regex

Time:10-31

I had a question I was able to solve for encrypting using regex and I like the solution just wondering if there is a way I can clean it up a bit? for the encryption im supposed to replace the vowels with these values and reverse the string adding aca to the end. just wondering if I can reduce the amount .replace lines thanks in advance

function encrypt(string) {
  let input=string.replace(/a/g, '0')
                  .replace(/e/g, '1')
                  .replace(/i/g, '2')
                  .replace(/o/g, '2')
                  .replace(/u/g, '3')
  return input.split("").reverse().join("") "aca"
              
}

CodePudding user response:

You might use a single replace with a callback function, and in the function map the values to the numbers.

function encrypt(string) {
    const obj = {'a': 0, 'e': 1, 'i': 2, 'o': 2, 'u': 3};
    return string
        .replace(/[aeiou]/g, m => obj[m])
        .split("")
        .reverse()
        .join("") "aca";
}

console.log(encrypt('this is an example, our example'));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Known characters one to one replacement, regexp is not required.

const encrypt = (str) => {
  const map = { a: '0', e: '1', i: '2', o: '2', u: '3' };
  return str.split('').map(ch => map[ch] || ch).reverse().join('')   'aca';
}

console.log(encrypt('hello mario'));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related