1

I've tried googling a bit but haven't had much success. What I'm trying to do is change every letter in a string to something else. For example "this is a string" would turn to something like "&@/- 52 - .'49-!"

So far I've got my string/phrase as

    let phrase = ['a', 'b', 'c'];

then afterwards

    phrase = phrase.map(phrase => {
    return phrase.replace('a', '-');
    return phrase.replace('b', '!');
    return phrase.replace('c', ',');
    return phrase.replace('d', ';'); 
    return phrase.replace('e', ',');
    return phrase.replace('f', '(');

.. all the way to Z, then

    });
    console.log(phrase); 

When I run it, I get this output

    [ '-', 'b', 'c' ]

but it should be this

    [ '-', '!', ',' ]

which means it's only 'translating' the first letter and skipping the rest,whereas I need it to translate the entire string.

I'd really appreciate if someone could point me in the right direction :)

0

2 Answers 2

4

I'd use an object organized by replace: replaceWith instead:

const replacements = {
  a: '-',
  b: '!',
  c: ',',
  d: ';',
  e: ',',
  f: '('
};
const input = ['a', 'b', 'c'];
const output = input.map(inputPhrase => replacements[inputPhrase]);
console.log(output);

If the phrases to be replaced can contain characters that can't be bare keys, enclose them in strings:

const replacements = {
  a: '-',
  b: '!',
  c: ',',
  d: ';',
  e: ',',
  f: '(',
  '###': 'foo'
};
const input = ['a', 'b', 'c', '###'];
const output = input.map(inputPhrase => replacements[inputPhrase]);
console.log(output);

Sign up to request clarification or add additional context in comments.

Comments

2

The return quits from the function - either reassign phrase each time:

let phrase = ['a', 'b', 'c'];

phrase = phrase.map(phrase => {
  phrase = phrase.replace('a', '-');
  phrase = phrase.replace('b', '!');
  phrase = phrase.replace('c', ',');
  phrase = phrase.replace('d', ';');
  phrase = phrase.replace('e', ',');
  return phrase.replace('f', '(');
});

console.log(phrase);

Or use an object (use toLowerCase to avoid case sensitivity - just remove it if you want different characters for a and A):

let phrase = ['a', 'b', 'c'];

const replace = {
  "a": "-",
  "b": "!",
  "c": ",",
  "d": ";",
  "e": ",",
  "f": "("
};

phrase = phrase.map(phrase => replace[phrase.toLowerCase()]);

console.log(phrase);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.