Home > database >  leave the original letter if can't find one to replace
leave the original letter if can't find one to replace

Time:10-10

I'm trying to transform a message with default font to the font "vaporwave", but when it finds a letter that isn't defined, it returns undefined, how could i make it skip that letter that wasn't defined and leave the original one?

font = {
    "A": "A",
    "B": "B",
    "C": "C",
    "D": "D",
    "E": "E",
    "F": "F",
    [...]
}

const string = "hello world"
const vapour = string.split('').map(letter => {
  return font[letter];
}).join('');

//return for example, "undefined EL L O [...]"
//i want: "h EL L O [...]"


CodePudding user response:

You can alternate the font[letter] with the original letter:

const vapour = string.split('').map(letter => {
  return font[letter] || letter;
}).join('');

Or, what I'd prefer would be to construct a regular expression from the keys of the object:

const pattern = new RegExp('['   Object.keys(font).join('')   ']', 'g');
const vapour = string.replace(pattern, char => font[char]);

CodePudding user response:

Use Nullish coalescing operator (??) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

const vapour = string.split('').map(letter => {
  return font[letter] ?? letter;
}).join('');

CodePudding user response:

Why not just check if the letter is present in the dictionary ?

font = {
    "A": "A",
    "B": "B",
    "C": "C",
    "D": "D",
    "E": "E",
    "F": "F",
}

const string = "ABCDEFG123"
const vapour = string.split('').map(letter => {
  if (letter in font) {
    return font[letter];
  } else {
    return letter
  }
}).join('');
console.log(string, "-->", vapour);

  • Related