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,"");
asked May 14, 2014 at 17:59
s_p
4,6788 gold badges60 silver badges95 bronze badges
2 Answers 2
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, '');
answered May 14, 2014 at 18:04
anubhava
791k67 gold badges604 silver badges671 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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'));
}
answered May 14, 2014 at 18:05
Barmar
789k57 gold badges555 silver badges669 bronze badges
Comments
lang-js
/myregex/and"/myregex/"are not the same thing..replacewithout a string to call it on.