2017-04-13 59 views
1

我有一段代碼,尋找鏈接,並將它們放入一個onClick事件:正則表達式將換行鏈路

var regex = /href\s?=\s?"\s?([\S]+)"/g; 
var newText = $sanitize(text).replace(regex, "onClick=\"window.open('$1', '_system', 'location=yes')\""); 

唯一的問題是,對於特別長的鏈接它看起來像一個換行符可能添加因爲當我嘗試點擊鏈接預期的結果不會發生(我也複製並粘貼鏈接到我的文本編輯器,似乎有一個換行符)。這裏是鏈接的例子:

window.open('http://somedomain.com/subscription/some-report-text/issue/the-deadliest-word-on-the- 
planet-could-bring-savvy-investors-extraordinary-profits/?u=000071340856&vid=TatDiU&a=MMP&o=9637385?u=000071340856&vid=8ALdFM&a=MMP&o=6530827?u=000071340856&vid=9Vm2j_&a=MMP&o=1652570?u=000071340856&vid=Cd_ME9&a=MMP&o=8995371', '_system', 'location=yes') 

有另一個正則表達式我可以運行擺脫換行符從我的新鏈接內?或者,我的第一個表情有什麼問題嗎?

p.s.學習正則表達式的祕訣是什麼?

+0

學習正則表達式的祕訣是瞭解它們不是一個通用工具,並且[不應該用於解析標記語言](http://stackoverflow.com/q/1732348/1255289)。 – miken32

+0

另一個祕訣就是了解並欣賞上世紀90年代jzw的名言。 「有些人在遇到問題時想'我知道,我會用正則表達式'。」現在他們有兩個問題。「 – miken32

回答

-1

修復你的正則表達式這樣的搭配完全鏈接:href\s?=\s?"\s?([\S\s]+)"

Demo

但在此之前,你應該這樣做:text = text.replace(/\s/, '')

$sanitize(text.replace(/\s/, '')).replace(...)

0

您應該正確解析DOM來找到鏈接。假設你已經jQuery加載,這是簡單的:(儘管它已經多年,因爲我已經使用過,所以藉此與一粒鹽)

$("a").on("click", function(e){ 
    e.preventDefault(); 
    window.open(this.href, '_system', 'location=yes'); 
}); 

否則native DOM methods將工作

var links = document.getElementsByTagName("a"); 
for (var i = 0; i < links.length; i++) { 
    links[i].addEventListener("click", function(e) { 
     e.preventDefault(); 
     e.stopPropagation(); 
     window.open(e.target.href, "_system", "location=yes"); 
    }); 
}