简体   繁体   English

如何从字符串中删除所有出现的任何给定字符?

[英]How to remove all occurrences of any given character from string?

My code: 我的代码:

    function removeFromString(mystring,char){

    let regex = new RegExp(char, 'g');
    let string;
    for(let i; i< mystring.length; i++){
        string = mystring.replace(regex, ''));

    }
    console.log(mystring);
}
removeFromString('Hello How are you','o');

This doesn't work. 这行不通。 Any idea what am I doing wrong? 知道我在做什么错吗?

The method String.replace() doesn't change the string, it creates a new string. 方法String.replace()不会更改字符串,它会创建一个新字符串。 Return the result of the replace. 返回替换的结果。

In addition, since you've used the g flag in the regex, it will replace all occurrences in the string, so you don't need the for loop. 另外,由于在正则表达式中使用了g标志,它将替换字符串中的所有匹配项,因此不需要for循环。

 function removeFromString(mystring, char) { const regex = new RegExp(char, 'g'); return mystring.replace(regex, ''); } console.log(removeFromString('Hello How are you', 'o')); 

You can also achieve the same thing with a loop, by rebuilding the string from all characters in the original string the are not the char : 您还可以通过循环来实现相同的目的,方法是从不是char的原始字符串中的所有字符重建字符串:

 function removeFromString(mystring, char) { let string = ''; for (let i = 0; i < mystring.length; i++) { if(mystring[i] !== char) string += mystring[i]; } return string; } console.log(removeFromString('Hello How are you', 'o')); 

You can simply use replace for it. 您可以简单地使用replace No need for loop. 无需循环。 like 喜欢

 var str = "How are you?"; console.log(str.replace(/o/g, "")) 

g flag is to replace all occurrences g标志是替换所有出现的事件

Or Just for fun. 或只是为了好玩。

 var str = "How are you?"; console.log(str.split("o").join('')) 

split string by your desired character. 按所需字符split字符串。 This will give you an array. 这会给你一个数组。 Now you can join this array with '' 现在您可以使用''加入该数组

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

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