標籤:javascript Regex replaceall textarea 替換
JavaScript中是沒有replaceAll的,只有replace,replace只能替換字元中的第一個字元,而且這個replace裡面不支援Regex,以達到replaceAll的目的。
不過可以自己寫一個JavaScript中的replaceAll,也不用寫到str.replaceAll,一點就能夠用的程度的程度,寫一個返回值為字串類型、處理之後的字串;形式參數為要處理的字串,要被替換的東西、要被替換成的東西的函數就可以了。
寫好一個JavaScript中的replaceAll可以對某些多行文字框從資料庫讀取資料,之後清理多行文字框不能被javascript中清理HTML函數,詳見《【JavaScript】某些字元不轉義可以導致網頁崩潰與涉及逸出字元的顯示方法》(點擊開啟連結),把<BR>清理成\r\n的問題,從而在多行文字框正常顯示的問題。這多見於一些編輯功能。
JavaScript的replaceAll函數如下:
function replaceAll(str,replaced,replacement){var reg=new RegExp(replaced,"g");str=str.replace(reg,replacement);return str;}
具體使用方式用一個例子來說明這個函數的利用,
比如網站有如下的表單,顯示如同word中的替換功能。
這個網頁的布局如下,很簡單,請注意裡面的ID即可:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>replaceAll</title></head><body><textarea id="str"></textarea><br />把<input type="text" id="replaced" />替換成<input type="text" id="replacement" /><button onclick="replaceAllTest()">go!</button></body></html>
GO按鈕首先呼叫指令碼中的replaceAllTest函數,把文字框中的內容,被替換的內容,要替換的內容拿過來。直接調用上文的replaceAll()函數,完成替換得到的字串,則替換文字框中的文本即可。
<script>function replaceAllTest(){var str=document.getElementById("str").value;var replaced=document.getElementById("replaced").value;var replacement=document.getElementById("replacement").value;str=replaceAll(str,replaced,replacement);document.getElementById("str").value=str;}function replaceAll(str,replaced,replacement){var reg=new RegExp(replaced,"g");str=str.replace(reg,replacement);return str;}</script>
【JavaScript】JavaScript中的replaceAll