Home > Software engineering >  Is there are any way to get change first and last letter in a string in JS?
Is there are any way to get change first and last letter in a string in JS?

Time:01-05

I need make some width function. It take a string and must to return an arrive with changed letters. For example:

enter code here

 let word = 'letter'
 function(word) {
 // code here
 return var // {letter, etterl, tterle, terlet, erlett, rlette]

CodePudding user response:

you can do this:

function permut(string) {
  if (string.length < 2) return string;

  const permutations = [];
  for (let i = 0; i < string.length; i  ) {
    const char = string[i];

    if (string.indexOf(char) !== i) continue;

    const remainingString =
      string.slice(0, i)   string.slice(i   1, string.length);

    for (const subPermutation of permut(remainingString))
      permutations.push(char   subPermutation);
  }
  return permutations;
}

console.log(permut("hello"));

CodePudding user response:

You can easily achieve the result if you first split the string, and then loop over the character array.

All you have to do is to push the first character at the end of the array on every iteration.

let word = 'letter';

function getResult(word) {
  const wordArray = word.split('');
  const result = [];
  for (let i = 0; i < word.length;   i) {
    result.push(wordArray.join(''));
    wordArray.push(wordArray.shift());
  }

  return result;
}

console.log(getResult(word));

  •  Tags:  
  • Related