修改数组中的每个单词
Modifying each word of an array
所以,我要做的是创建一个函数,允许用户输入一个字符串,然后它将以猪拉丁文输出字符串。下面是我的函数:
function wholePigLatin() {
var thingWeCase = document.getElementById("isLeaper").value;
thingWeCase = thingWeCase.toLowerCase();
var newWord = (thingWeCase.charAt(0));
if (newWord.search(/[aeiou]/) > -1) {
alert(thingWeCase + 'way')
} else {
var newWord2 = thingWeCase.substring(1, thingWeCase.length) + newWord + 'ay';
alert(newWord2)
}
}
我如何让它识别每个单词,然后按照上面的方式修改每个单词?
修改函数以接受参数并返回值
function wholePigLatin(thingWeCase) {
thingWeCase = thingWeCase.toLowerCase();
var newWord = (thingWeCase.charAt(0));
if (newWord.search(/[aeiou]/) <= -1) {
newWord = thingWeCase.substring(1, thingWeCase.length) + newWord + 'ay';
}
else{
newWord = thingWeCase + 'way';
}
return newWord;
}
那么你可以这样做:
var pigString = str.split(" ").map(wholePigLatin).join(" ");
将字符串拆分为单词,将每个单词传递给函数,然后将输出与空格连接在一起。
如果您总是想从同一源获取数据,您也可以从函数中获取数组并将其分割/连接。
使用javascript的split()方法。在这种情况下,你可以取var
arrayOfWords = thingWeCase.split(" ")
这将字符串拆分为字符串数组,拆分点位于每个空格处。然后,您可以轻松地遍历结果数组中的每个元素。
编写一个在循环中调用单个单词函数的函数:
function loopPigLatin(wordString) {
words = wordString.split(" ");
for( var i in words)
words[i] = wholePigLatin(words[i]);
return words.join(" ");
}
当然,要像这样调用它,您需要对原始函数做一点改动:
function wholePigLatin(thingWeCase) {
// everything after the first line
return newWord2; // add this at the end
}
然后这样调用loopPigLatin
:
document.getElementById("outputBox").innerHTML = loopPigLatin(document.getElementById("isLeaper").value);
您可以使用regexp匹配单词并将其替换为callback:
var toPigLatin = (function () {
var convertMatch = function (m) {
var index = m.search(/[aeiou]/);
if (index > 0) {
return m.substr(index) + m.substr(0,index) + 'ay';
}
return m + 'way';
};
return function (str) {
return str.toLowerCase().replace(/('w+)/g, convertMatch);
};
}());
console.info(toPigLatin("lorem ipsum dolor.")); // --> oremlay ipsumway olorday.
相关文章:
- Javascript-从随机的单词数组中创建段落
- 将组成单词的字符添加到数组的开头
- undercore返回数组中对象的indes,其中单词存在于对象中的句子中
- Javascript-在一个数组中搜索整个单词,并创建一个符合条件的新数组
- 在两个位置显示数组中的随机单词
- 如果输入包含数组中的任何单词
- 单词数组到字符串
- Javascript/Node AI-如何使用match从单词数组中重复单词
- 在单词数组中查找相似的单词
- 在单词数组中搜索单词
- 将句子字符串拆分为单词数组,然后将单词数组拆分为单词数组中的字符数组
- underscore.js基于单词数组从字符串中删除文本
- 从JavaScript中的单词数组中查找第n个字符
- Coffeescription在页面上的单词数组中进行迭代
- 我们如何用单词数组填充一组
- 用正则表达式连续收集单词数组中的任意单词
- 试图响应从node.js http服务器中分割成单词数组的文本
- 在mark.js中为单独的单词数组设置样式
- 将字符串拆分为单词数组以查找“最长”
- 王牌编辑器查找全部不起作用.需要所有带有 dif 的单词.数组中的值