我需要用字符串中的索引 + 1 替换字符串中的每个元音。
(函数名称 = vowel2index)
输出示例:
vowel2index('this is my string') == 'th3s 6s my str15ng'
我希望这个例子展示了我正在尝试做的事情。我试过如下使用替换方法:
str.replace(/[aeiou]/gi, str.indexOf(/[aeiou]/gi);
但这并没有解决问题。我也尝试了下面的代码,但我无法弄清楚从 IF 语句到哪里(我还没有使用数组元音):
function vowel2index(str) {
let vowels = ["a", "e", "i", "o", "u"];
let arr = [];
for(i = 0; i < str.length; i++){
if (str[i] === /[aeiou]/gi) {
arr.push(str.replace(str[i], indexOf(str[i])+1));
}
感谢任何帮助。仅供引用,此问题来自代码战。
最佳答案
你快到了。 .replace
函数 accepts an offset
parameter包含当前匹配项的索引,因此您可以只使用 replacer 函数,并返回该偏移量加一。不需要元音数组,只需要使用模式中的元音字符集:
function vowel2index(str) {
return str.replace(/[aeiou]/gi, (vowel, offset) => offset + 1);
}
console.log(vowel2index('this is my string')); // == 'th3s 6s my str15ng');
关于javascript - 使用 JavaScript 将字符串中的元音替换为其在字符串中的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53531239/