![](/img/trans.png)
[英]How to find if the first letter of a string is a vowel in javascript
[英]just change the vowel to the next letter in javascript
首先我要證明句子中是否有元音,如果有元音就用下一個字母代替。 不是元音的字母不會被替換,但在輸出中保持不變。
我所做的編碼結果變得不合適。
function changeVocals(str){
var split = str.split('')
var vocal = 'aiueo'
var change = 'bjvfp'
var a = ''
for (var i = 0; i < split.length; i++) {
for (var j = 0; j < vocal.length; j++) {
if (vocal[j] === split[i]) {
a = a + change
} else {
a = a + split[i]
}
}
}
return a
}
console.log(changeVocals('Alexa')); //'Blfxb'
我希望 'Alexa' 的輸出是 'Blfxb',但實際輸出是這句話似乎是重復的。
實際輸出:AAAAAllllleeebjvfpexxxxxbjvfpaaaa
您可以使用對象來映射值,並根據大小寫替換匹配的值
const mapper = { a: 'b', e: 'f', i: 'j', o: 'p', u: 'v', A: 'B', E: 'F', I: 'J', O: 'P', U: 'V' } const changeVocals = (string) => { return string.replace(/[aeiou]/gi, match => mapper[match]) } console.log(changeVocals('Alexa'));
可以用map
來完成;
var vowels = ['a', 'e', 'i', 'o', 'u']; var text = 'Alexa'; var result = text.split('').map(x => vowels.indexOf(x.toLowerCase())>=0 ? String.fromCharCode(x.charCodeAt()+1) : x).join(''); console.log(result);
function changeVocals(str){ return [...str].map(letter => "aeiouAEIOU".contains(letter) ? String.fromCharCode(letter.charCodeAt(0)+1) : letter).join(''); } changeVocals("Alexa");
但不知何故,代碼片段無法識別contains
函數
我在您的嘗試中發現了幾個錯誤。 我試圖修復它以使其正常工作,如下所示。 但是你的嘗試真的很接近。 我希望我的評論能幫助您了解您犯錯誤的那兩個方面。
function changeVocals(str) {
var split = str.split('');
var vocal = 'aiueo';
var change = 'bjvfp';
var a = ''
for (var i = 0; i < split.length; i++) {
for (var j = 0; j < vocal.length; j++) {
// When there is a match we will not continue
// so break out of the loop.
if (vocal[j] === split[i]) {
// this test if the match is lowercase to lowercase
a = a + change[j];
break;
} else if (vocal[j].toUpperCase() === split[i]) {
// this test if the match is uppercase to uppercase
a = a + change[j].toUpperCase();
break;
}
}
// When there is no match found we just copy the input
// character to the resulting string.
// We figured there is no match found when we see
// that the resulting string length is less than the current
// value of i
if (a.length < i + 1) a = a + split[i];
}
return a;
}
console.log(changeVocals('Alexa'));
//'Blfxb'
function convertot(string) { const vowels = ['a', 'e', 'i', 'o', 'u']; let str = ''; for (let i = 0; i < string.length; i += 1) { const element = string[i]; const isPresent = vowels.findIndex((f) => { return f === element.toLowerCase(); }); if (isPresent !== -1) { str += String.fromCharCode(element.charCodeAt() + 1); } else { str += element; } } return str; } const text = 'Alexa'; const modified = convertot(text); console.log(text); console.log(modified);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.