JavaScript實現文本目標字符替換和一鍵全部替換

需求描述:

實現在文本中替換目標字符,以及一鍵全部替換功能。

技術點:

利用string的replace實現替換第一個找到的目標字符。

replace(searchValue: string | RegExp, replaceValue: string): string;

利用string的replaceAll實現一鍵替換全部找到的目標字符。

replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string;

完整demo示例:

效果圖:

完整代碼:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>js實現文本字符替換全部替換</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實現文本目標字符替換和一鍵全部替換的文章就介紹到這瞭,更多相關js文本替換內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: