简体   繁体   中英

How do I keep spaces in a string?

I am working with a substitution cipher, where each letter of the alphabet is represented by a letter from the substituted alphabet.

function substitution(input, alphabet) {
  let str = '';
  let result = input.split('');
  alphabet = alphabet.split('');

  for (let i = 0; i < result.length; i++) {
    if (alphabet.includes(result[i])) {
      str += alphabet[i];
      console.log(str);
    }
  }
  //console.log(str);
  return str;
}

substitution('ab c', 'plmoknijbuhvygctfxrdzeswaq');

The output I'm expecting is 'pl m' , however I am getting 'plo' as the space moves to the next letter since there isn't a space in the substituted alphabet. Is there a way to preserve that space without using regex?

If the letter is in your alphabet, you add the encrypted letter. But if it's not in the alphabet, you don't do anything. You should still add it, just not encrypted:

function substitution(input, alphabet) {
  let str = '';
  let result = input.split('');
  alphabet = alphabet.split('');

  for (let i = 0; i < result.length; i++) {
    if (alphabet.includes(result[i])) {
      str += alphabet[i];
      console.log(str);
    } else {
      str += result[i];
    }
  }
  //console.log(str);
  return str;
}

substitution('ab c', 'plmoknijbuhvygctfxrdzeswaq');

I'd use a regular expression instead - match and replace word characters. Use a replacer function that returns the index of the match count on the string, and increments the match count:

 function substitution(input, alphabet) { let i = 0; return input.replace( /\w/g, () => alphabet[i++] ); } console.log(substitution('ab c', 'plmoknijbuhvygctfxrdzeswaq'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM