我的应用要求是,如果一个单词有一个像“anupam”这样的元音,那么在它的最后一个元音添加“xy”之后。所以它的结果应该是“anupxy”。但是,如果两个元音继续一个字,那么它应该是:
Oa = Oaxy
and au = auxy
Gardenhire = Gardxy
Parker = Parkxy
Arney = Arnxy
There are 4 rules.
1. The name cuts off at the second vowel and is replaced by 'xy.'
2. connected vowels count as a single and should stay together.
3. EXCEPTION: when the last letter is 'x' another 'x' is not added.
4. Names with only two connected vowels should have "xy" added to the end
我不知道我的错误在哪里,我的代码是:
function doit(userName) {
var temp = userName.toLowerCase();
var vowels = "aeiouy"
var count = 0;
if(userName) {
for(var i=0; i<temp.length; i++) {
if( vowels.indexOf(temp.charAt(i)) > -1 ) {
count++;
if(count==1) {
while( vowels.indexOf(temp.charAt(++i)) != -1 );
i--;
} else
break;
}
}
userName = userName.substr(0, i);
if( userName.charAt(userName.length-1) == 's' )
userName += "y";
else
userName += "sy";
} else
userName = 'Take a lap, Dummy';
return userName.toUpperCase();
}
答案 0 :(得分:2)
正则表达是最佳选择。
var word = "anumap";
var transformed = word.replace(/(\w+[aeiou]+).*/i, " $1xy");
我创造了一个互动小提琴:http://jsfiddle.net/53qH6
“\ w +”表示匹配任何单词字符。这将获得最后一个元音之前的所有字母。 其中的[]和元音是我们正在寻找的东西,括号外的+表示必须至少有一个元音。 “。*”表示匹配接下来的任何内容(最后一个元音之后的任何内容) 括号表示将其捕获到变量($ 1)中。
答案 1 :(得分:1)
我建议您使用正则表达式,尤其是在使用解释语言时。更简单的代码,也可能更好的性能。参见:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
答案 2 :(得分:1)
function doit(userName) {
var str = userName || "";
var vowels = ["a","e","i","o","u"];
var suffix = "xy";
var str_arr = str.split("");
var str_arr_rev = str_arr.reverse();
$.each(str_arr_rev, function (i, item) {
if ($.inArray(item.toLowerCase(), vowels) > -1) {
last_vowel_index = i;
return false;
}
});
if (last_vowel_index == -1) {
$.each(str_arr_rev, function (i, item) {
if (item.toLowerCase() == "y") {
last_vowel_index = i;
return false;
}
});
}
if (last_vowel_index > -1)
str_arr_rev[last_vowel_index] = str_arr_rev[last_vowel_index] + suffix;
return str_arr_rev.reverse().join("");
}
答案 3 :(得分:1)
不确定要求的第二部分,
但是,如果两个元音继续一个字,那么它应该是:
Oa = Oaxy and au = auxy -Anup
尝试这种模式
html
<input type="text" value="" /><br />
<div id="name"></div>
JS
编辑
原始作品未将“anupam”转换为“ANUPAXY”,regex
es仍可使用调整
$(function () {
$("input").on("change", function(e) {
$("#name")
.html(function (index, o) {
var v = /[aeiou]+.$/gi;
var o = $(e.target).val();
var n = v.test(o);
return (n ? String(o.replace(/[^aeiou]$/gi, "") + "xy").toUpperCase() : o)
});
});
})
jsfiddle http://jsfiddle.net/guest271314/nB9Qc/
另见
Is this the shortest javascript regex to find all uppercase consonants?
How to negate specific word in regex?
Break string after specific word and put remains on new line (Regex)