Converting a string to NATO phonetic alphabets in JavaScript


Problem

We are required to write a JavaScript function that takes in a string and converts it into NATO phonetic alphabet.

The 26 code words are as follows: Alfa, Bravo, Charlie, Delta, Echo, Foxtrot, Golf, Hotel, India, Juliett, Kilo, Lima, Mike, November, Oscar, Papa, Quebec, Romeo, Sierra, Tango, Uniform, Victor, Whiskey, X-ray, Yankee, Zulu.

Example

Following is the code −

 Live Demo

const str = 'this is simple string';
const convertToNato = (str = '') => {
   let nato = {
      a: 'Alfa',
      b: 'Bravo',
      c: 'Charlie',
      d: 'Delta',
      e: 'Echo',
      f: 'Foxtrot',
      g: 'Golf',
      h: 'Hotel',
      i: 'India',
      j: 'Juliett',
      k: 'Kilo',
      l: 'Lima',
      m: 'Mike',
      n: 'November',
      o: 'Oscar',
      p: 'Papa',
      q: 'Quebec',
      r: 'Romeo',
      s: 'Sierra',
      t: 'Tango',
      u: 'Uniform',
      v: 'Victor',
      w: 'Whiskey',
      x: 'Xray',
      y: 'Yankee',
      z: 'Zulu'
   }
   let arr = [...str];
   return arr
   .filter((letter) => letter !== " ")
   .map((letter) => {
      if( /[^a-z]/.test(letter.toLowerCase()) ) { return letter }
      else { return nato[letter.toLowerCase()]; }
   }).join(' ');
};
console.log(convertToNato(str));

Output

Following is the console output −

Tango Hotel India Sierra India Sierra Sierra India Mike Papa Lima Echo Sierra Tango Romeo India November Golf

Updated on: 17-Apr-2021

565 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements