我有一个url扩展名列表,我希望使用正则表达式替换字符串,以便像这样捕获大写和小写:
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,"");
当我尝试使用数组和循环这样清理它时,我收到一个错误。任何人都可以帮我解决语法问题
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,"");
答案 0 :(得分:5)
您可以这样做,而不是在循环中多次运行替换:
str = str.replace(/\.(com|net|org|gov|edu|ad|ae|ac|int)/gi, '');
答案 1 :(得分:3)
您需要创建一个RegExp
对象。您还需要将.replace
应用于字符串,并分配结果。
for (ii = 0; ii < arr.length; ii++) {
str = str.replace(new Regexp('\\.' + arr[ii], 'i'));
}