js实现文本目标字符替换和一键全部替换

781 阅读1分钟

js实现文本目标字符替换和一键全部替换

需求描述

实现在文本中替换目标字符,以及一键全部替换功能。

技术点

利用string的replace实现替换第一个找到的目标字符。

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

利用string的replaceAll实现一键替换全部找到的目标字符。

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

完整demo示例

效果图

image.png

完整代码

<!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>