我試圖清理HTML輸入字段。我想保留一些標籤,但不是全部標籤,因此在讀取元素值時不能只使用.text()
。我在Safari中使用JavaScript中的正則表達式遇到了一些問題。這裏的代碼段的(我複製從另一個SO線程的答案正則表達式的該位):JavaScript替換()正則表達式太貪婪
aString.replace (/<\s*a.*href=\"(.*?)\".*>(.*?)<\/a>/gi, '$2 (Link->$1)') ;
這裏是失敗的樣本輸入:
<a href="http://blar.pirates.net/black/ship.html">Go here please.</a></p><p class="p1"><a href="http://blar.pirates.net/black/ship.html">http://blar.pirates.net/black/ship.html</a></p>
的想法是,在href將得到拉出並輸出爲純文本旁邊的文本將被鏈接。所以上面的輸出最終應該是這樣的:
Go here please (Link->http://blar.pirates.net/black/ship.html)
http://blar.pirates.net/black/ship.html (Link->http://blar.pirates.net/black/ship.html)
然而,正則表達式被抓一路下跌到第一比賽第二</a>
標籤,所以我失去輸出的第一行。 (實際上,只要錨元素相鄰,它就會抓取到列表中最遠的那個元素。)輸入是一個長字符串,不會通過CR/LF或任何其他元素進行分割。
我已經使用非貪婪的標誌是這樣的(注意第二個問號)嘗試:
/<\s*a.*href=\"(.*?)\".*?>(.*?)<\/a>/ig
但是,這似乎並沒有改變任何東西(至少不是在幾個測試儀/解析器我嘗試過,其中之一在這裏:http://refiddle.com)。也嘗試了/U
標誌,但這沒有幫助(或這些解析器不認識它)。
有什麼建議嗎?的
href=\"(.*?)\"
基本上
只是讓你知道,你的正則表達式將不會在防範'了'標籤足夠了,他們可以在href屬性中使用單引號或沒有引號。或者他們可以使用內聯onclick或其他事件處理程序。 – Markasoftware
幸運的是,這不是一個公共系統,所以我不關心安全性。這只是試圖從粘貼到此字段的文本中刪除格式。 (這是一個內部評論系統 - 它們正在DB中的父記錄上輸入評論。) – Cronk