简体   繁体   中英

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. 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.

 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 :

 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. No need for loop. like

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

g flag is to replace all occurrences

Or Just for fun.

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

split string by your desired character. This will give you an array. Now you can join this array with ''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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