2012-10-31 50 views
2

我想替換「。」到像[點]從下面輸入到低於輸出替換「。」。在多個網址中以[字符串]排成一個字符串

輸入

令牌,這是一個test.for的問題。在stackoverflow.com最好的地方學習。節目。測試www.wikipedia.com

輸出

這是一個test.for的問題。在stackoverflow [點] COM最好的地方學習。節目。測試萬維網[點]維基百科[點] com

問題

  1. 是有可能test.for我們不能用好正則表達式像/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}/gi我認爲最好使用類似下面更好
  2. 也許我找到了解決辦法;

found = string.match(/([a-zA-Z0-9]+\.(com|co\.cc)|more\.domains)/gi);

這項工作很好,我不得不加入/替換他們的原始字符串的問題。任何變通辦法如how can we filter elements in array with regex in array with javascript?

你將如何解決這個問題? btw即時通訊使用nodejs其他語言是可以接受的。

感謝

+0

什麼'www.stackoverflow.com'? – Phrogz

+0

是的,可以算。對於缺乏信息感到抱歉。但沒有http:// etc – user1780413

+0

但它應該是'www [dot] stackoverflow [dot] com'或'www.stackoverflow [dot] com'? – Phrogz

回答

3

這正確處理www.example.com

tld = ["com", "org", "edu", "net"] // feel free to add more 

var input = "this is a test.for a question. at www.stackoverflow.com " 
    + "the best place to learn. " 
    + "programming.test wikipedia.com and windows.microsoft.edu"; 


re = new RegExp('\\S+\\.(' + tld.join('|') + ')\\b', 'g') 

var dotted = input.replace(re, function($0) { 
    return $0.replace(/\./g, "[dot]"); 
}); 

// this is a test.for a question. at www[dot]stackoverflow[dot]com the best place to learn. 
// programming.test wikipedia[dot]com and windows[dot]microsoft[dot]edu 
1
var input = "this is a test.for a question. at stackoverflow.com the best place to learn. programming. test wikipedia.com"; 
var dotted = input.replace(/(\S+)\.(com|org|edu|net)\b/gi, '$1[dot]$2'); 
// "this is a test.for a question. at stackoverflow[dot]com the best place to learn. programming. test wikipedia[dot]com" 
+0

www [dot]維基百科[dot] .com如何像'/\b(\S+)\.(com|org|edunetnet)\b|\bwww\.(\S+){3,} \。(com | org | edu | net)\ b/gi,'www [dot] $ 1 [dot] $ 2''(仍在工作) – user1780413

+0

編輯*我們可以做類似dotted.replace(/ \ bwww \ 。(\ S +)\ b/gi,'www [dot] $ 1');':)還有嗎? – user1780413

相關問題