JavaScript 替换字符串:使用 replace() 方法和正则表达式
使用 JavaScript 中的 replace() 方法来替换指定的字符串。replace() 方法需要传入两个参数,第一个参数为要替换的字符串或正则表达式,第二个参数为替换后的字符串或替换函数。
示例代码:
var str = document.getElementById('chatgpt-response').value; // 获取文本框中的字符串
var replacedStr = str.replace('要替换的字符串', '替换后的字符串'); // 使用 replace() 方法替换指定的字符串
document.getElementById('chatgpt-response').value = replacedStr; // 将替换后的字符串赋值给文本框
需要注意的是,上述示例代码只会替换第一个匹配到的字符串。如果想要替换所有匹配到的字符串,可以使用正则表达式,并在正则表达式中使用 /g 标志。
示例代码:
var str = document.getElementById('chatgpt-response').value; // 获取文本框中的字符串
var replacedStr = str.replace(/要替换的字符串/g, '替换后的字符串'); // 使用正则表达式替换所有匹配到的字符串
document.getElementById('chatgpt-response').value = replacedStr; // 将替换后的字符串赋值给文本框
原文地址: https://www.cveoy.top/t/topic/mzGS 著作权归作者所有。请勿转载和采集!