简体   繁体   English

替换字符串中的所有元音 javascript

[英]replace all vowels in a string javascript

I am trying to write a function that will remove all vowels in a given string in JS.我正在尝试编写一个 function ,它将删除 JS 中给定字符串中的所有元音。 I understand that I can just write string.replace(/[aeiou]/gi,"") but I am trying to complete it a different way...this is what I have so far... thank you!我知道我可以只写 string.replace(/[aeiou]/gi,"") 但我正在尝试以不同的方式完成它......这就是我到目前为止所拥有的......谢谢!

I first made a different function called IsaVowel that will return the character if it is a vowel...我首先制作了一个名为 IsaVowel 的不同 function,如果它是元音,它将返回字符......

function withoutVowels(string) {

var withoutVowels = "";
for (var i = 0; i < string.length; i++) {
    if (isaVowel(string[i])) {
 ***not sure what to put here to remove vowels***
       }
  }
    return withoutVowels;
}

Use accumulator pattern. 使用累加器模式。

 function withoutVowels(string) { var withoutVowels = ""; for (var i = 0; i < string.length; i++) { if (!isVowel(string[i])) { withoutVowels += string[i]; } } return withoutVowels; } function isVowel(char) { return 'aeiou'.includes(char); } console.log(withoutVowels('Hello World!')); 

I tried doing this problem by first splitting the string into an array, while also creating an array of vowels. 我尝试通过首先将字符串拆分为一个数组来完成此问题,同时还创建了一个元音数组。 Then go through each element in the string array and check whether it's in my vowel array. 然后遍历字符串数组中的每个元素,然后检查它是否在我的元音数组中。 If it is not in my vowel array, push it to the withoutVowels array. 如果它不在我的元音数组中,请将其推入noVowels数组中。 At the end of the for loop, join all elements in the withoutvowels array and return. 在for循环的末尾,将所有元素加入novovowels数组中并返回。

function withoutVowels(string) {
            var strWithoutVowels =  [];
            string = string.split('');
            var vowels = ['a', 'e', 'i', 'o', 'u'];
            for (var i = 0; i < string.length; i++) {
                if (vowels.indexOf(string[i]) < 0) {
                    strWithoutVowels.push(string[i])
                }
            }
            strWithoutVowels = strWithoutVowels.join('');
            return strWithoutVowels;
        }
        console.log(withoutVowels('Hello World!'))

I think the easiest way is to use a regex;我认为最简单的方法是使用正则表达式; it's cleaner and faster compared to all your loops.与所有循环相比,它更干净、更快。 Below is the code.下面是代码。

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

the gi in the code means no matter the case whether uppercase or lowercase so long as its a vowel, it will be removed代码中的 gi 表示无论大小写只要是元音都会被去掉

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM