Question

I have a list of url extensions that i want to string replace using regex so that both upper and lower case is captured like this:

str = str.replace(/\.net/i,"")
.replace(/\.com/i,"")
.replace(/\.org/i,"")
.replace(/\.net/i,"")
.replace(/\.int/i,"")
.replace(/\.edu/i,"")
.replace(/\.gov/i,"")
.replace(/\.mil/i,"")
.replace(/\.arpa/i,"")
.replace(/\.ac/i,"")
.replace(/\.ad/i,"")
.replace(/\.ae/i,"")
.replace(/\.af/i,"");

When i try to clean this up using arrays and loops like so, i get an error. Can anyone help me with syntax please

var arr = [ "net","com","org","net","int","edu","gov","mil","arpa","ac","ad","ae"];

str = str.replace(/\.com/i,"")
for(ii==0;ii<=arr.length;ii++){
  .replace('/\.'+arr[ii]+'/i',"") // i know this '/\.' and '/i' should not be a string but how would i write it?
} 
.replace(/\.af/i,"");
Was it helpful?

Solution 2

You need to create a RegExp object. You also need to apply .replace to the string, and assign the result.

for (ii = 0; ii < arr.length; ii++) {
    str = str.replace(new Regexp('\\.' + arr[ii], 'i'));
}

OTHER TIPS

You can just do like this instead of running replace multiple times in a loop:

str = str.replace(/\.(com|net|org|gov|edu|ad|ae|ac|int)/gi, '');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top