尝试我自己的字符串方法删除元音 [英] Trying my own string method to remove vowels

查看:93
本文介绍了尝试我自己的字符串方法删除元音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了此函数以从字符串中删除小写元音.此功能不适用于某些字符串.如果字符串中出现多个相同的元音,则仅删除一个元音. 谢谢您的帮助.

I have written this function to remove lowercase vowels from a string. This function is not working for some strings. If the string has more than one occurrence of the same vowel only one vowel is being removed. Thank you for your help.

var string = "heelloo world";
var vowel = ["a", "e", "i", "o", "u"];

String.prototype.character = function name() {
    var i;
    for ( i = 0; i < vowel.length; i++) {
        var secondLoop = string.length;
        for ( j = 0; j < secondLoop; j++) {
            if (vowel[i] == string.charAt(j)) {
                string = string.slice(0, j).concat(string.slice(j + 1, secondLoop));
            }

        }
    }
}

string.character();
console.log(string);
//hello wrld

推荐答案

从字符串中删除一个字符时,您将跳过循环中的下一个字符,因为该字符串现在短了一个字符,但指针()仍指向同一位置.删除字符时,您需要减少计数器.

When you remove a character from the string, you're skipping the next character in the loop because the string is now one character shorter but the pointer (j) still points at the same position. You need to decrement the counter when you remove a character.

var string = "heelloo world";
var vowel = ["a", "e", "i", "o", "u"];

String.prototype.character = function name() {
    var i;
    for ( i = 0; i < vowel.length; i++) {
        var secondLoop = string.length;
        for ( j = 0; j < secondLoop; j++) {
            if (vowel[i] == string.charAt(j)) {
                string = string.slice(0, j).concat(string.slice(j + 1, secondLoop));
                j--;           // take the removed character into account
                secondLoop--;  // string is now one character shorter
            }

        }
    }
}

string.character();
console.log(string);

也就是说,除非有充分的理由避免使用正则表达式,否则使用正则表达式实现同一操作会容易得多.

That said, it would be much easier to implement the same thing using a regex, unless you have a compelling reason to avoid it.

var string = "heelloo world";

string = string.replace( /[aeiou]/g, '' );

console.log(string);  // hll wrld

这篇关于尝试我自己的字符串方法删除元音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆