JavaScript實現(xiàn)文本目標字符替換和一鍵全部替換
更新時間:2022年06月07日 11:09:22 作者:??靈扁扁????
這篇文章主要介紹了JavaScript實現(xiàn)文本目標字符替換和一鍵全部替換,文章圍繞主題展開詳細的內容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
需求描述:
實現(xiàn)在文本中替換目標字符,以及一鍵全部替換功能。
技術點:
利用string的replace實現(xiàn)替換第一個找到的目標字符。
replace(searchValue: string | RegExp, replaceValue: string): string;
利用string的replaceAll實現(xiàn)一鍵替換全部找到的目標字符。
replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string;
完整demo示例:
效果圖:
完整代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js實現(xiàn)文本字符替換全部替換</title> </head> <body> <textarea name="textarea" id="text" rows="10" cols="50">標準測試技術,紅糖標準,酸奶標準,瀏覽器運行標準。</textarea> <div> 查找<input id="oldVal" placeholder="要查找的內容" value=""> 替換<input id="newVal" placeholder="用來替換的內容"> <button onclick="replace()">替換</button> <button onclick="replace('all')">全部替換</button> </div> <script type="text/javascript"> function replace (type) { let newText = '' const text = document.getElementById('text').value || '' const oldVal = document.getElementById('oldVal').value || '' const newVal = document.getElementById('newVal').value || '' if (type === 'all') { // 全部替換 newText = text.replaceAll(oldVal, newVal) } else { // 替換找到的第一個 newText = text.replace(oldVal, newVal) } // 將替換后的內容,更新到文檔上 document.getElementById('text').value = newText } </script> </body> </html>
到此這篇關于JavaScript實現(xiàn)文本目標字符替換和一鍵全部替換的文章就介紹到這了,更多相關js文本替換內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
相關文章
關于動態(tài)執(zhí)行代碼(js的Eval)實例詳解
下面小編就為大家?guī)硪黄P于動態(tài)執(zhí)行代碼(js的Eval)實例詳解。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08JS實現(xiàn)表單驗證功能(驗證手機號是否存在,驗證碼倒計時)
js實現(xiàn)表單驗證功能,通過js代碼驗證手機號是否存在驗證碼倒計時功能,代碼簡單易懂非常不錯,具有參考借鑒價值,感興趣的朋友一起看看吧2016-10-10