最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - Given a String, Move The First Letter of Each Word to The End of Each Word, Then Add "ay" To The End

programmeradmin2浏览0评论

So far I have:

function pigIt(str) {

  //split string into array of words
  let words = str.split(" ");

  //loop through array of words
  for (let i = 0; i < words.length; i++) {

    //loop through individual words
    for (let j = 0; j < words.length; j++) {

      //get first word in words
      let firstWord = words[0];

      //get first character in first word
      let firstChar = firstWord[0];

      //Create new word without first character
      let unshiftedWord = firstWord.unshift(0);

      //move first character to the end
      let newWord = unshiftedWord.push(firstChar) + "ay";

      return newWord;

    }
  }
}

console.log(pigIt('Pig latin is cool'));

For now, I would just like to return "igPay". Then, I will bine the strings together to form a new string.

But it doesn't like firstWord.unshift(0);. It's saying:

TypeError: firstWord.unshift is not a function.

But .unshift() is a function? Why isn't that working?

Once I can get a new word, I should be able to bine the newWords together into a newString, although there's probably a more efficient way than creating new for-loops for each individual word.

EDIT: I'm looking to write this function with traditional function declaration, not with arrow notation.

EDIT 2 After implementing @Ori Drori's code, my function looks like:

function pigIt(str) { 

  newString = str.replace(/(\S)(\S+)/g, '$2$1ay');
  return newString;
}

console.log(pigIt('Pig latin is cool'));

And it works - but I don't understand what str.replace(/(\S)(\S+)/g, '$2$1ay'); is doing, exactly.

So far I have:

function pigIt(str) {

  //split string into array of words
  let words = str.split(" ");

  //loop through array of words
  for (let i = 0; i < words.length; i++) {

    //loop through individual words
    for (let j = 0; j < words.length; j++) {

      //get first word in words
      let firstWord = words[0];

      //get first character in first word
      let firstChar = firstWord[0];

      //Create new word without first character
      let unshiftedWord = firstWord.unshift(0);

      //move first character to the end
      let newWord = unshiftedWord.push(firstChar) + "ay";

      return newWord;

    }
  }
}

console.log(pigIt('Pig latin is cool'));

For now, I would just like to return "igPay". Then, I will bine the strings together to form a new string.

But it doesn't like firstWord.unshift(0);. It's saying:

TypeError: firstWord.unshift is not a function.

But .unshift() is a function? Why isn't that working?

Once I can get a new word, I should be able to bine the newWords together into a newString, although there's probably a more efficient way than creating new for-loops for each individual word.

https://www.codewars./kata/520b9d2ad5c005041100000f/train/javascript

EDIT: I'm looking to write this function with traditional function declaration, not with arrow notation.

EDIT 2 After implementing @Ori Drori's code, my function looks like:

function pigIt(str) { 

  newString = str.replace(/(\S)(\S+)/g, '$2$1ay');
  return newString;
}

console.log(pigIt('Pig latin is cool'));

And it works - but I don't understand what str.replace(/(\S)(\S+)/g, '$2$1ay'); is doing, exactly.

Share Improve this question edited Apr 3, 2019 at 18:31 HappyHands31 asked Apr 3, 2019 at 18:12 HappyHands31HappyHands31 4,10119 gold badges65 silver badges117 bronze badges 5
  • 2 firstWord is a string. unshift isn't a method on string: developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – peinearydevelopment Commented Apr 3, 2019 at 18:15
  • Okay so .unshift() will only work for an array - not a string. I guess I could turn the string into an array? – HappyHands31 Commented Apr 3, 2019 at 18:17
  • firstWord[0] does not give you an error, since it just returns a non-existing value of property "0" of the string. – PM 77-1 Commented Apr 3, 2019 at 18:18
  • On the other hand, you have return inside an inner loop. How many iterations do you expect? – PM 77-1 Commented Apr 3, 2019 at 18:19
  • It should iterate through every word in the string so my return is in the wrong place. – HappyHands31 Commented Apr 3, 2019 at 18:20
Add a ment  | 

4 Answers 4

Reset to default 3

You can use a RegExp (regex101) and String.replace(). The regex catches the head (1st letter) and tail (the other letters) of each word (actually sequence of non space values). Use the replacement ($2$1ay) to rebuild the word in pig latin.

const pigIt = (str) => str.replace(/(\w)(\w+)/g, '$2$1ay')

console.log(pigIt('Pig latin is cool'));

How does the replace work:

  • The regex collects the 1st word character (\w) and assigns it to $1
  • The regex collects the rest of the word's characters and assigns them to $2
  • The replacement defines that the new string would be $2 then $1 and then "ay"

Note: I've used \S to catch all non space characters.

A simpler way to that is using map() and join().

Note: that according to codewars example only ay is added to string containing aplhabets not !. So you should test whether the the element of array is aplhabet or not using test().

All the tests in the codewars are passed for following solution.

function pigIt(str){
  return str.split(' ').map(x =>/[a-zA-Z]+/.test(x) ? x.slice(1)+x[0]+'ay' : x).join(' ');
}
console.log(pigIt('Pig latin is cool'));

Without arrow function.

function pigIt(str){
  return str.split(' ').map(function(x){ 
      return /[a-zA-Z]+/.test(x) ? x.slice(1)+x[0]+'ay' : x;
  }).join(' ');
}
console.log(pigIt('Pig latin is cool'));

Simple for loop

Here is the code using simple for loop

function pigIt(str){
  str = str.split(' ');
  for(let i = 0;i<str.length;i++){
    if(/[a-zA-Z]/.test(str[i])){
      str[i] = str[i].slice(1) + str[i][0] + 'ay';
    } 

  }
  return str.join(' ');
}
console.log(pigIt('Pig latin is cool'));

unshift in not an method on string

You can simply split on space and than map and swap places and add ay and join them with space again.

let str = `Pig latin is cool`

let op = str.split(' ').map(e=>  e.substr(1,) +e[0] + 'ay').join(' ')

console.log(op)

Without arrow function

let str = `Pig latin is cool`

let op = str.split(' ').map(function(e){
  return  e.substr(1,) +e[0] + 'ay'
}).join(' ')

console.log(op)

Try this it will work and without Regex

function pigIt(str){
       let arr = str.split(" ");
       let newArr = [];
       for ( let i = 0 ; i < arr.length ; i++ ) {
          if ( arr[i] === "!" || arr[i] === "?" ){
             newArr.push(arr[i]);
          } else { 
             let s = arr[i].slice(1)+arr[i].charAt(0)+"ay"
             newArr.push(s)
          }
        }
      return newArr.join(" ")
    } 

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论