正则表达式:Javascript中的ccTLD通配符检测/删除?

时间:2013-12-18 23:04:22

标签: javascript regex string

我有一个像这样的网址:

  

http://xenodesystems.blogspot .COM /2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html

但那里的“。com”可能因国家/地区而异,因此该网址也适用:

  

http://xenodesystems.blogspot .MX /2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html   http://xenodesystems.blogspot。它 /2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html   http://xenodesystems.blogspot .FR /2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html

我需要做的是将“xenodesystems.blogspot。*”替换为“blog.xenodesystems.com”,并保留其余的网址,例如:

  

http://blog.xenodesystems.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html

这可能与javascript有关吗?我知道blogger可以重定向一个域,但我需要在纯Javascript中明确地做到这一点。我知道这是可能的,这只是找到正确的正则表达式的问题,对吧?

2 个答案:

答案 0 :(得分:1)

试试这个(JSFIDDLE)。没有正则表达式,所以效率更高:

var str="http://xenodesystems.blogspot.mx/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html";
 function xIndexOf(Val, Str, x)  
 {  
   if (x <= (Str.split(Val).length - 1)) {  
     Ot = Str.indexOf(Val);  
     if (x > 1) { for (var i = 1; i < x; i++) { var Ot = Str.indexOf(Val, Ot + 1) } }  
     return Ot;
   }
 }
var slash = (xIndexOf('/',str,3));
var dot = (xIndexOf('.',str,2));
str = str.substring(0,dot)+".com"+str.substring(slash)
alert(str)

xIndexOf函数取自here

答案 1 :(得分:0)

我认为这就是你的意思:

var urls = [
  'http://xenodesystems.blogspot.mx/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html',
  'http://xenodesystems.blogspot.it/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html',
  'http://xenodesystems.blogspot.fr/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html',
  'http://xenodesystems.blogspot.com.au/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html',
];

var ret = new Array;
var len = urls.length;
for (var i = 0; i < len; ++i) {
  ret.push(urls[i].replace(/xenodesystems.blogspot(?:\.[a-zA-Z]+)+/,'xenodesystems.blogspot.com'));
}
console.log(ret);

<强>输出

["http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html",
"http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html",
"http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html",
"http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html"]

这是fiddle