欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript實(shí)現(xiàn)文本目標(biāo)字符替換和一鍵全部替換

 更新時(shí)間:2022年06月07日 11:09:22   作者:??靈扁扁????  
這篇文章主要介紹了JavaScript實(shí)現(xiàn)文本目標(biāo)字符替換和一鍵全部替換,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下

需求描述:

實(shí)現(xiàn)在文本中替換目標(biāo)字符,以及一鍵全部替換功能。

技術(shù)點(diǎn):

利用string的replace實(shí)現(xiàn)替換第一個(gè)找到的目標(biāo)字符。

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

利用string的replaceAll實(shí)現(xiàn)一鍵替換全部找到的目標(biāo)字符。

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

完整demo示例:

效果圖:

完整代碼:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>js實(shí)現(xiàn)文本字符替換全部替換</title>
</head>
<body>

<textarea name="textarea" id="text" rows="10" cols="50">標(biāo)準(zhǔn)測(cè)試技術(shù),紅糖標(biāo)準(zhǔn),酸奶標(biāo)準(zhǔn),瀏覽器運(yùn)行標(biāo)準(zhǔn)。</textarea>
<div>
  查找<input
    id="oldVal"
    placeholder="要查找的內(nèi)容"
    value="">
  替換<input id="newVal" placeholder="用來替換的內(nèi)容">
  <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 {
    // 替換找到的第一個(gè)
    newText = text.replace(oldVal, newVal)
  }
  // 將替換后的內(nèi)容,更新到文檔上
  document.getElementById('text').value = newText
}
</script>
</body>
</html>

到此這篇關(guān)于JavaScript實(shí)現(xiàn)文本目標(biāo)字符替換和一鍵全部替換的文章就介紹到這了,更多相關(guān)js文本替換內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論