且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

尝试我自己的字符串方法删除元音

更新时间:2023-11-13 19:03:10

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

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