简体   繁体   中英

3 While Loops into a Single Loop?

I have to remove the commas, periods, and hyphens from an HTML text value. I do not want to write all 3 of these while loops, instead I only want one loop (any) to do all of this.

I already tried a while with multiple && and if else nested inside but i would always only just get the commas removed.

while(beg.indexOf(',') > -1)
{
    beg = beg.replace(',','');
    document.twocities.begins.value= beg;
}

while(beg.indexOf('-') > -1)
{
    beg = beg.replace('-','');
    document.twocities.begins.value= beg;
}
while(beg.indexOf('.') > -1)
{
    beg= beg.replace('.','');
    document.twocities.begins.value= beg;

}

You can do all this without loops by using regex. Here is an example of removing all those characters using a single regex:

 let str = "abc,de.fg,hij,1-2,34.56.7890" str = str.replace(/[,.-]/g, "") console.log(str) 

Use regex like below.

 let example = "This- is a,,., string.,"; console.log(example.replace(/[-.,]+/g, "")); 

A single call to the replace function and using a regular expression suffice:

document.twocities.begins.value = beg = beg.replace(/[,.-]/g, "");

Regular expressions are a pattern matching language. The pattern employed here basically says "every occurrence of one of the characters . , , , - )". Note that the slash / delimits the pattern while the suffix consists of flags controlling the matching process - in this case it is g (global) telling the engine to replace each occurrence ( as opposed to the first only without the flag ).

This site provides lots of info about regular expressions, their use in programming and implementations in different programming environments.

There are several online sites to test actual regular expression and what they match (including explanations), eg. Regex 101 .

Even more details ... ;): You may use the .replace function with a string as the first argument (as you did in your code sample). However, only the first occurrence of the string searched for will be replaced - thus you would have to resort to loops. Specs of the .replace function (and of JS in general) can be found here .

No loops are necessary for this in the first place.

You can replace characters in a string with String.replace() and you can determine which characters and patterns to replace using regular expressions .

 let sampleString = "This, is. a - test - - of, the, code. "; console.log(sampleString.replace(/[,-.]/g, "")); 

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