猪拉丁语翻译器 - JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10306899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pig Latin Translator - JavaScript
提问by Gcap
So for my cit class I have to write a pig Latin converter program and I'm really confused on how to use arrays and strings together. The rules for the conversion are simple, you just move the first letter of the word to the back and then add ay. ex: hell in English would be ellhay in pig Latin I have this so far:
因此,对于我的 cit 类,我必须编写一个猪拉丁语转换器程序,而且我对如何一起使用数组和字符串感到非常困惑。转换规则很简单,你只需将单词的第一个字母移到后面,然后加上 y。例如:英语中的地狱将是猪拉丁语中的 ellhay 到目前为止我有这个:
<form name="form">
<p>English word/sentence:</p> <input type="text" id="english" required="required" size="80" /> <br />
<input type="button" value="Translate!" onClick="translation()" />
<p>Pig Latin translation:</p> <textarea name="piglat" rows="10" cols="60"></textarea>
</form>
<script type="text/javascript">
<!--
fucntion translation() {
var delimiter = " ";
input = document.form.english.value;
tokens = input.split(delimiter);
output = [];
len = tokens.length;
i;
for (i = 1; i<len; i++){
output.push(input[i]);
}
output.push(tokens[0]);
output = output.join(delimiter);
}
//-->
</script>
I'd really appreciate any help I can get!
我真的很感激我能得到的任何帮助!
回答by user5173781
function translate(str) {
str=str.toLowerCase();
var n =str.search(/[aeiuo]/);
switch (n){
case 0: str = str+"way"; break;
case -1: str = str+"ay"; break;
default :
//str= str.substr(n)+str.substr(0,n)+"ay";
str=str.replace(/([^aeiou]*)([aeiou])(\w+)/, "ay");
break;
}
return str;
}
translate("paragraphs")
回答by scottm
I think the two things you really need to be looking at are the substring()
method and string concatentation (adding two strings together) in general. Being that all of the objects in the array returned from your call to split()
are strings, simple string concatentation works fine. For example, using these two methods, you could move the first letter of a string to the end with something like this:
我认为您真正需要注意的两件事是一般的substring()
方法和字符串连接(将两个字符串加在一起)。由于从调用返回的数组中的所有对象split()
都是字符串,因此简单的字符串连接工作正常。例如,使用这两种方法,您可以将字符串的第一个字母移动到末尾,如下所示:
var myString = "apple";
var newString = mystring.substring(1) + mystring.substring(0,1);
回答by elclanrs
If you're struggling with arrays this might be a bit complicated, but it's concise and compact:
如果您正在为数组而苦苦挣扎,这可能有点复杂,但它简洁紧凑:
var toPigLatin = function(str) {
return str.replace(/(^\w)(.+)/, 'ay');
};
Demo: http://jsfiddle.net/elclanrs/2ERmg/
演示:http: //jsfiddle.net/elclanrs/2ERmg/
Slightly improved version to use with whole sentences:
稍微改进的版本以用于整个句子:
var toPigLatin = function(str){
return str.replace(/\b(\w)(\w+)\b/g, 'ay');
};
回答by Yup.
Here's my solution
这是我的解决方案
function translatePigLatin(str) {
var newStr = str;
// if string starts with vowel make 'way' adjustment
if (newStr.slice(0,1).match(/[aeiouAEIOU]/)) {
newStr = newStr + "way";
}
// else, iterate through first consonents to find end of cluster
// move consonant cluster to end, and add 'ay' adjustment
else {
var moveLetters = "";
while (newStr.slice(0,1).match(/[^aeiouAEIOU]/)) {
moveLetters += newStr.slice(0,1);
newStr = newStr.slice(1, newStr.length);
}
newStr = newStr + moveLetters + "ay";
}
return newStr;
}
回答by Art Cutillo
This code is basic, but it works. First, take care of the words that start with vowels. Otherwise, for words that start with one or more consonants, determine the number of consonants and move them to the end.
这段代码是基本的,但它有效。首先,注意以元音开头的单词。否则,对于以一个或多个辅音开头的单词,确定辅音的数量并将它们移到末尾。
function translate(str) {
str=str.toLowerCase();
// for words that start with a vowel:
if (["a", "e", "i", "o", "u"].indexOf(str[0]) > -1) {
return str=str+"way";
}
// for words that start with one or more consonants
else {
//check for multiple consonants
for (var i = 0; i<str.length; i++){
if (["a", "e", "i", "o", "u"].indexOf(str[i]) > -1){
var firstcons = str.slice(0, i);
var middle = str.slice(i, str.length);
str = middle+firstcons+"ay";
break;}
}
return str;}
}
translate("school");
回答by Liviu Iancu
Another way of doing it, using a separate function as a true or false switch.
另一种方法是使用单独的函数作为真或假开关。
function translatePigLatin(str) {
// returns true only if the first letter in str is a vowel
function isVowelFirstLetter() {
var vowels = ['a', 'e', 'i', 'o', 'u', 'y'];
for (i = 0; i < vowels.length; i++) {
if (vowels[i] === str[0]) {
return true;
}
}
return false;
}
// if str begins with vowel case
if (isVowelFirstLetter()) {
str += 'way';
}
else {
// consonants to move to the end of string
var consonants = '';
while (isVowelFirstLetter() === false) {
consonants += str.slice(0,1);
// remove consonant from str beginning
str = str.slice(1);
}
str += consonants + 'ay';
}
return str;
}
translatePigLatin("jstest");
回答by Pilar Mireles
this is my solution code :
这是我的解决方案代码:
function translatePigLatin(str) {
var vowel;
var consonant;
var n =str.charAt(0);
vowel=n.match(/[aeiou]/g);
if(vowel===null)
{
consonant= str.slice(1)+str.charAt(0)+”ay”;
}
else
{
consonant= str.slice(0)+”way”;
}
var regex = /[aeiou]/gi;
var vowelIndice = str.indexOf(str.match(regex)[0]);
if (vowelIndice>=2)
{
consonant = str.substr(vowelIndice) + str.substr(0, vowelIndice) + ‘ay';
}
return consonant;
}
translatePigLatin(“gloove”);
回答by Pilar Mireles
Yet another way.
又一种方式。
String.prototype.toPigLatin = function()
{
var str = "";
this.toString().split(' ').forEach(function(word)
{
str += (toPigLatin(word) + ' ').toString();
});
return str.slice(0, -1);
};
function toPigLatin(word)
{
//Does the word already start with a vowel?
if(word.charAt(0).match(/a*e*i*o*u*A*E*I*O*U*/g)[0])
{
return word;
}
//Match Anything before the firt vowel.
var front = word.match(/^(?:[^a?e?i?o?u?A?E?I?O?U?])+/g);
return (word.replace(front, "") + front + (word.match(/[a-z]+/g) ? 'a' : '')).toString();
}
回答by ninjagecko
Your friends are the string function .split
, and the array functions .join
and .slice
and .concat
.
你的朋友是字符串函数.split
,以及阵列功能.join
和.slice
和.concat
。
- https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array#Accessor_methods
- https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String#Methods_unrelated_to_HTML
- https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array#Accessor_methods
- https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String#Methods_unrelated_to_HTML
warning:Below is a complete solution you can refer to once you have finished or spent too much time.
警告:以下是一个完整的解决方案,您可以在完成或花费过多时间后参考。
function letters(word) {
return word.split('')
}
function pigLatinizeWord(word) {
var chars = letters(word);
return chars.slice(1).join('') + chars[0] + 'ay';
}
function pigLatinizeSentence(sentence) {
return sentence.replace(/\w+/g, pigLatinizeWord)
}
Demo:
演示:
> pigLatinizeSentence('This, is a test!')
"hisTay, siay aay esttay!"